【问题标题】:Why Won't These Jest Mocks Reset?为什么这些笑话不会重置?
【发布时间】: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


    【解决方案1】:

    如果您导入的模块是一个对象,您需要独立地模拟每个导出的函数:

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

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

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

    然后重置

    HttpService.post.mockReset()
    

    【讨论】:

    • 感谢您迄今为止的帮助,这还没有工作。我确实在 mocks 文件夹中将 HttpService.post 模拟为手动模拟。模拟仍然不会回到我提供的实现。你有像我使用过的导入语法这样工作的代码吗?谢谢! @andreas
    • 登录HttpService.post会得到什么
    • 如果我登录HttpService.post,它说它在重置之前和之后是一个笑话,但如果在重置之前调用并记录HttpService.post(),它会说Promise { <rejected> { payload: 'rejected' } },在重置之后undefined它是没有从 mocks 文件夹设置回实现,知道如何解决吗?
    • 也许 mockRestore() 就是你要找的东西
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果您想为文件中的某些测试模拟模块(使用模拟工厂),但为其他测试取消模拟 - 这对我有用:

      describe("some tests", () => {
        let subject;
      
        describe("with mocks", () => {
          beforeAll(() => {
            jest.isolateModules(() => {
              jest.doMock("some-lib", () => ({ someFn: jest.fn() })); // doMock isnt hoisted with babel
              subject = require('./module-that-imports-some-lib');
            });
          });
      
          // ... tests when some-lib is mocked
        });
      
        describe("without mocks - restoring mocked modules", () => {
          beforeAll(() => {
            jest.isolateModules(() => {
              jest.unmock("some-lib");
              subject = require('./module-that-imports-some-lib');
            });
          });
      
          // ... tests when some-lib is NOT mocked
      
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-14
        • 2020-03-24
        • 1970-01-01
        • 2013-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-09
        相关资源
        最近更新 更多