为什么这些Jest Mocks重置?

时间:2018-01-31 15:37:10

标签: javascript unit-testing testing redux jestjs

我有测试代码影响其他测试并导致它们失败。当我孤立地运行测试用例时,一切都过去了,但是当我运行整个套装时,会有很多失败。如果你看下面的两个测试,你可以看到我在测试中覆盖了一个模拟模块,导致抛出异常。

HttpService.post

运行此行后,所有需要原始jest.resetMock模拟的测试都会失败,因为它们不会重置。在测试之后,如何正确地将我的模拟恢复到导入的模拟?我在beforeEach中尝试了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' }); }); }); }); }) }); ,并尝试了类似的每个jest方法,但没有任何效果。我知道答案可能是直截了当的,但我对我在网上读到的有关如何导入代码的所有差异感到困惑(es6 import,commonJs)。谢谢!

<html>

<body>
  <form method="POST" action="" />
  </br>
  <label>Name</label>
  <input type="text" name="name" required onkeypress="javascript:return checkNum(event)" />
  </br>
  </br>
  <input type="submit" value="submit" />
  </form>
</body>
<script>
  function checkNum() {

    if ((event.keyCode > 64) || (event.keyCode > 96 && event.keyCode < 123) || event.keyCode == 8)
      return true;
    else {
      alert("Please enter only char");
      return false;
    }

  }
</script>

2 个答案:

答案 0 :(得分:9)

如果导入作为对象的模块,则需要独立模拟每个导出的函数:

import HttpService from '../../services/httpService';
jest.mock('../../services/httpService', ()=>({
  post: jest.fn()
});

稍后您可以像这样设置模拟的行为

HttpService.post.mockImplementation(()=>Promise.reject({ payload: 'rejected' }))

并重置

HttpService.post.mockReset()

答案 1 :(得分:1)

我有类似的问题。事实证明,这个https://github.com/facebook/jest/pull/5720是问题所在,将Jest升级到至少23.0.0版本可以解决此问题。在撰写本文时,23.6是Jest的最新稳定版本。

在我的情况下,mockRejectedValueOnce似乎没有被重置,因为当我在先前的测试中注释掉mockRejectedValueOnce方法时,我的后续测试(有问题的测试)再次起作用。因此重置方法无效。