wit*_*s14 9 javascript testing unit-testing jestjs redux
我有测试代码影响其他测试并导致它们失败.当我孤立地运行测试用例时,一切都过去了,但是当我运行整个套装时,会有很多失败.如果你看下面的两个测试,你可以看到我在测试中覆盖了一个模拟模块,导致抛出异常.
HttpService.post = jest.fn(() => {
return Promise.reject({ payload: 'rejected' });
});
Run Code Online (Sandbox Code Playgroud)
在运行此行之后,所有需要原始HttpService.post模拟的测试都会失败,因为它们未被重置.在测试之后,如何正确地将我的模拟恢复到导入的模拟?我已经尝试jest.resetMock过beforeEach和类似于每个jest方法,但没有任何效果.我知道答案可能是直截了当的,但我对我在网上读到的有关如何导入代码的所有差异感到困惑(es6 import,commonJs).谢谢!
import HttpService from '../../services/httpService';
import handleErrors from '../../utilities/handleErrors';
jest.mock('../../services/httpService');
jest.mock('../../utilities/handleErrors');
describe('async actions', () => {
beforeEach(() => {
store = mockStore({});
});
describe('some describe that wraps both tests', () => {
describe('a describe that wraps just the first test', () => {
test(`creates ${constants.actions.REQUEST_SAVE_NOTE_FAILURE}`, () => {
HttpService.post = jest.fn(() => {
return Promise.reject({ payload: 'rejected' });
});
const expectedActions = [
{ type: constants.actions.REQUEST_SAVE_NOTE },
{ type: constants.actions.REQUEST_SAVE_NOTE_FAILURE, data: { payload: 'rejected' } },
];
return store.dispatch(actions.saveNote({
id: 1,
note: 'note',
})).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
});
describe('a describe that wraps just the second test', () => {
test(`creates ${constants.actions.REQUEST_SAVE_NOTE}
and ${constants.actions.RECEIVE_SAVE_NOTE}`, () => {
params = {
body: {
prospects: [1],
note: 'note',
},
};
const expectedActions = [
{ type: constants.actions.REQUEST_SAVE_NOTE },
{ type: constants.actions.RECEIVE_SAVE_NOTE, data: { payload: 'payload' } },
];
return store.dispatch(actions.saveNote({
id: 1,
note: 'note',
})).then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(HttpService.post).toBeCalledWith({ ...params, url: '/api/prospect/add-note' });
});
});
});
})
});
Run Code Online (Sandbox Code Playgroud)
如果导入作为对象的模块,则需要独立模拟每个导出的函数:
import HttpService from '../../services/httpService';
jest.mock('../../services/httpService', ()=>({
post: jest.fn()
});
Run Code Online (Sandbox Code Playgroud)
稍后您可以像这样设置模拟的行为
HttpService.post.mockImplementation(()=>Promise.reject({ payload: 'rejected' }))
Run Code Online (Sandbox Code Playgroud)
并重置
HttpService.post.mockReset()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3791 次 |
| 最近记录: |