【发布时间】:2018-07-10 18:48:23
【问题描述】:
我的测试代码会影响其他测试并导致它们失败。当我单独运行测试用例时,一切都通过了,但是当我运行整个套装时,会有很多失败。如果您查看下面的两个测试,您可以看到我在测试中覆盖了一个模拟模块以导致抛出异常。
HttpService.post = jest.fn(() => {
return Promise.reject({ payload: 'rejected' });
});
运行此行后,所有需要原始 HttpService.post 模拟的测试都会失败,因为它们没有被重置。在此测试之后,如何正确地将我的模拟恢复为导入的模拟?我在 beforeEach 中尝试过jest.resetMock 以及几乎所有类似的玩笑方法,但没有任何效果。我知道答案可能是直截了当的,但我对我在网上读到的关于如何导入代码(es6 导入、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' });
});
});
});
})
});
【问题讨论】:
标签: javascript unit-testing testing redux jestjs