HMR*_*HMR 6 javascript reactjs jestjs
我正在尝试这样的事情:
const useSelector = jest.fn();
jest.mock('react-redux', () => ({
useSelector,
}));
Run Code Online (Sandbox Code Playgroud)
然后尝试做这样的事情:
useSelector.mockReturnValueOnce({});
shallow(
<ComponentUsingUseSelector />
);
Run Code Online (Sandbox Code Playgroud)
这会给我一个错误:
的模块工厂
jest.mock()不允许引用任何超出范围的变量。
因此,如果我不能使用超出范围的变量进行模拟,那么我将如何为每个测试返回不同的值?
简化版本,也可以使用:
import * as redux from 'react-redux'
jest
.spyOn(redux, 'useSelector')
.mockReturnValueOnce('first call')
Run Code Online (Sandbox Code Playgroud)
mockReturnValueOnce另外,最好只存根存储的必要部分,而不是依赖于多次调用:
const locale = 'en'
const state = {
application: { locale },
}
jest
.spyOn(redux, 'useSelector')
.mockImplementation((callback) => callback(state))
Run Code Online (Sandbox Code Playgroud)
在阅读了大量没有做我(认为)需要做的事情的文章和文档之后,以下内容似乎有效;终于找到了一个可以的。
import { useSelector } from 'react-redux';
jest.mock('react-redux', () => ({
useSelector: jest.fn(),
}));
describe('some test', () => {
it('do something', () => {
useSelector.mockImplementation(() => ('hello world'));
shallow(
<ComponentUsingUseSelector />
);
Run Code Online (Sandbox Code Playgroud)
如果多次调用我可以这样做:
describe('some test', () => {
it('do something', () => {
useSelector.
.mockReturnValueOnce('first call')
.mockReturnValueOnce('second call')
shallow(
<ComponentUsingUseSelector />
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16564 次 |
| 最近记录: |