[英]Jest mock redux toolkit actions/store files
我在 React.js 应用程序中使用 Redux 工具包,我提取的逻辑如下:
商店.tsx
const history = createHashHistory();
const middleware = [
...getDefaultMiddleware().concat(routerMiddleware(history)),
];
const Store = configureStore({
reducer: {
router: connectRouter(history) as Reducer<any, any>,
/* my reducers */
}, middleware
});
MySlice.tsx
import {createSlice} from '@reduxjs/toolkit';
const initialState = {
/* content of my state */
};
const mySlice = createSlice(
{
name: "myState",
initialState,
reducers: {
myAction: (state: MyState) => {
// Whatever here...
}
},
extraReducers: builder => {
/* My extra reducers */
}
});
export const MySlice = mySlice;
然后我有我的 function:
MySuperFunc.tsx
export const superFunc = () => {
/* content of my function */
const {myAction} = MySlice.actions;
Store.dispatch(myAction({my: 'payload'}));
};
我想用 Jest 对它进行单元测试。 我想模拟我的 Store/MySlice 的内容,因为configureStore
和createSlice
执行额外的逻辑并且似乎需要一些配置。
我对有关mock
、 setMock
和spyOn
的 React.js 最佳实践和文档有点迷失了。
superFunc.spec.ts
const dispatchMockFn = jest.fn();
// Sol: 1
jest.mock('<< path >>/Store', () => ({dispatch: dispatchMockFn )});
// Sol: 2
jest.setMock('<< path >>/Store', {dispatch: dispatchMockFn});
// Sol: 3
jest.spyOn(Store, 'dispatch');
describe('superFunc', () => {
it('should call store', () => {
superFunc();
return expect(dispatchMockFn).toHaveBeenCalledWith(/* results of myAction({my: 'payload'}) */);
});
});
似乎很正常,因为我使用了“Store”,它不只导出 object,我们里面有一些额外的代码(createHistory 等)。
我搜索了一个完全模拟一个模块的解决方案,这就是我尝试 setMock/mock 的原因,它改变了一点错误但知道它抱怨MySlice
(extraReducers) 说我的 promises.fulfilled/rejected 没有定义等。
但我不想 go 深入 Store/Slice 配置,我只想模拟文件内容。
有什么想法/建议吗?
我找到了解决方案:
jest.mock
工厂必须改编自您的导出( export default VS. export const = {...} )
示例 1: MySuperFunc.tsx(默认导出)
export default ({superFunc: () => 'hello world'});
单元测试:
import superFunc from './MySuperFunc';
jest.mock('./MySuperFunc', () => ({superFunc: jest.fn()});
it('should return toto', () => {
(MySuperFunc.superFunc as any).mockReturnValue('toto');
return expect(MySuperFunc.superFunc).toHaveBeenCalledWith('toto');
});
但是,在示例 2 中,如果您通过以下方式更改导出:
// MySuperFunc.tsx
export const MyVariable = {superFunc: () => 'hello world'});
您的jest.mock
必须改编为:
jest.mock('./MySuperFunc', () => ({MyVariable: {superFunc: jest.fn()}});
因此,当我重新提出问题时,我有两个选择:
export default
更改切片文件中的导出jest.mock
包括{MySlice: {actions: {myAction: () => '...'}}}
抱歉,这个主题显然与“redux 工具包”无关,而是更多关于如何处理 typescript 文件中的导出内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.