【发布时间】:2020-03-20 08:52:33
【问题描述】:
我在 Jest 没有提升以“mock”为前缀声明的模拟函数时遇到问题 据我了解,这应该根据jest docs 工作
我有一个 redux 操作,它对另一个依赖项做了一些事情。 在依赖模块上调用方法的结果随后会与另一个操作一起分派。
如何在依赖模块AuthUtils 中模拟resume 的实现。调用 thunk 会引发错误,因为 resume 方法未定义
Actions.js
import { setUser } from '../../src/actions/UserActions';
import AuthUtils from '../utils/AuthUtils'; //dependent es6 class
const auth = new AuthUtils();
export const resumeSession = () => async (dispatch, getState) => {
try {
const resumeResult = await auth.resume(); // wait for result
dispatch(setUser(resumeResult)); //dispatch setUser with result
} catch() {
}
};
Actions.test.js:
import { resumeSession } from '../../src/actions/AuthActions';
import { setUser } from '../../src/actions/UserActions';
// auto mock UserActions
jest.mock('../../src/utils/UserActions');
// Mock resume method of AuthUtils using module factory param
// The mockResume here is undefined, but I expected because it begins with mock it would be hoisted along with the jest.mock call
// "An exception is made for variables that start with the word 'mock'." -- from the docks
const mockResume = jest.fn(() => Promise.resolve({ user: { things } }));
jest.mock('../../src/utils/AuthUtils', () => {
return jest.fn().mockImplementation(() => {
return { resume: mockResume };
});
});
describe('resumeSession', () => {
it('dispatches complete', async () => {
const mockDispatch = jest.fn();
const mockGetState = jest.fn();
await resumeSession()(mockDispatch, mockGetState);
expect(setUser).toHaveBeenCalledWith({ user: { things } });
// Test blows up because AuthUtils#resume is not a function
});
});
【问题讨论】:
标签: ecmascript-6 redux jestjs