javascript - 是否可以重新评估导入的 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()
但他们没有帮助。
解决方案
推荐阅读
- javascript - 刷新后JavaScript未定义变量
- spring - antMatcher 和 mvcMatcher 的区别
- java - 如何从 CSV 文件中获取特定数据
- python - 如何读取 DataFrame 中的特定单元格并写入其中
- flutter - flutter google_sign_in crash : __exceptionPreprocess + 294
- c# - C# itext pdf 创建者希腊字体不显示
- assembly - Why does my register print a value on its own (without using any system call)?
- swift - Swift & Firebase - Split data for user info?
- oracle - Currently Executing Procedure Name within the Package
- azure - 如何在 Application Insights Analytics 中对图表/箱进行零填充