tl;drNot toHaveBeenCall 给了我一个错误,因为之前的测试调用了这个函数。
我正在尝试对我的减速器功能进行单元测试。
function reducer(previousState, action) {
const { type } = action;
switch (type) {
case '1':
return {};
case '2':
return {};
default:
if (!type.startsWith('@@redux')) console.error(`Action type: '${type}' has no corresponding reducer.`);
return previousState;
}
}
我模拟控制台错误
let consoleErrorSpy;
beforeAll(() => {
consoleErrorSpy = jest.spyOn(global.console, 'error')
.mockImplementation(jest.fn); // mute console errors
});
我测试控制台错误
it('should print a console error if unknown action was given', () => {
reducer({}, { type: 'unknown' });
expect(consoleErrorSpy.mock.calls[0][0])
.toBe(`Action type: 'unknown' has no corresponding reducer.`);
});
紧接着,我测试了 if 案例
it('should not print a console error, if action came from redux internals', () => {
reducer({}, { type: '@@redux/INTERNAL_ACTION' });
expect(consoleErrorSpy).not.toHaveBeenCalled();
});
但是我收到此错误"预期的模拟函数不会被调用,但它被调用:"操作类型:"未知"没有相应的化简器。
这来自之前的测试。 我可以在创建新函数之前刷新函数的调用吗?
您需要在每次测试前清除模拟:
consoleErrorSpy.mockClear()
有关此内容的更多信息,请参阅文档。