首页 > 解决方案 > 是否可以重新评估导入的 ES6 模块?

问题描述

我正在尝试为 redux 应用程序编写单元测试。我有一个共同点store.js

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

import rootReducer from './root-reducer';

export default createStore(rootReducer, applyMiddleware(thunk));

和测试文件:

// necessary imports and mocks

describe('store', () => {
  beforeEach(() => {
    redux.createStore.mockClear();
    redux.applyMiddleware.mockClear();
    jest.resetModules()
  });

  it('should create the store properly', async () => {
    const stubMiddleware = jest.fn();
    redux.applyMiddleware.mockImplementation(() => stubMiddleware);

    await import('./store');

    expect(redux.createStore).toHaveBeenCalledTimes(1);
    expect(redux.createStore).toHaveBeenCalledWith(rootReducer, stubMiddleware);
  });

  it('should apply thunk middleware', async () => {
    redux.applyMiddleware.mockImplementation(() => {});

    await import('./store');

    expect(redux.applyMiddleware).toHaveBeenCalledTimes(1);
    expect(redux.applyMiddleware).toHaveBeenCalledWith(thunk);
  });
});

不幸的是,第二个测试用例将失败,因为 store 模块在第一次导入时只评估一次,并且我在每次测试后清除所有模拟。

其实这个问题很具体,但问题更广泛。我们有很多工具需要为我们的模块添加副作用,比如这里,创建一个商店。如何测试这些副作用?我的第一个解决方案是导出一种getStore()方法,它是单例 DP 的一种实现,但同样,在这种情况下,模块是由单例实例有状态的,在某些情况下可能需要重新评估。

我也试过jest.resetModules()jest.isolateModules()但他们没有帮助。

标签: javascriptjestjses6-modules

解决方案


推荐阅读