使用Jest测试分派其他2个功能的Redux动作?
我有一个函数(一个Redux动作),它调用2个函数.我不知道如何用Jest进行测试:
I have a function (a Redux action) which calls 2 functions. I can't figure how how to test this with Jest:
这是我的功能:
import doSomething from 'redux/do-something';
import doSomethingElse from 'redux/do-something-else';
export default () => async dispatch => {
await dispatch(doSomething());
dispatch(doSomethingElse());
};
这是我的测试
import doSomething from 'redux/do-something';
import doSomethingElse from 'redux/do-something-else';
import functionToTest from 'redux/function-to-test'
describe("functionToTest", ()=>{
jest.mock('redux/do-something');
jest.mock('redux/do-something-else');
const dispatch = jest.fn();
test('my test', ()=>{
functionToTest()(dispatch);
console.log(dispatch.mock.calls); // This returns an anonymous function
console.log(doSomething) // This returns undefined
})
})
您似乎想模拟do-something
和do-something-else
的默认导出,并测试它们是否被测试代码调度了.
It looks like you are wanting to mock the default export for do-something
and do-something-else
and test that they get dispatched by the code under test.
如果是这种情况,那么您可以这样做:
If that is the case then you can do it like this:
import functionToTest from 'redux/function-to-test'
jest.mock('redux/do-something', () =>
() => 'do something mock'
);
jest.mock('redux/do-something-else', () =>
() => 'do something else mock'
);
describe("functionToTest", () => {
test('my test', async () => { // <= async test function
const dispatch = jest.fn();
await functionToTest()(dispatch); // <= await the Promise
expect(dispatch.mock.calls[0][0]).toBe('do something mock'); // Success!
expect(dispatch.mock.calls[1][0]).toBe('do something else mock'); // Success!
});
});
详细信息
您可以将模块工厂函数作为第二个参数传递给jest.mock
,并且Jest
将使用调用该函数的结果作为在测试期间导入模块时返回的结果.
You can pass a module factory function as the second paramter to jest.mock
and Jest
will use the result of calling the function as what it gives back when the module is imported during the test.
jest.mock
调用被babel-jest
挂起,并在代码文件中的所有其他内容之前运行.当在测试函数中定义了jest.mock
时,无法吊装 jest.mock
调用应移至测试文件的顶级范围.
jest.mock
calls get hoisted by babel-jest
and run before everything else in the code file. The hoisting doesn't work right when jest.mock
is defined in a test function so the jest.mock
calls should be moved to the top level scope of the test file.
被测函数为async
,因此请使用async
测试函数和await
Promise
来确保其在断言之前已完成.
The function under test is async
so use an async
test function and await
the Promise
to make sure it has completed before asserting.