在我的 React 项目中,我构建了许多 Action Creator。我现在正在为他们编写 React 测试库测试。通过这些测试,我绝对想使用我现有的 Redux 存储。以下是一些正在运行的现有测试代码:
const configureStore = (defaultState) => {
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
rootReducer,
defaultState,
composeEnhancers(applyMiddleware(thunkMiddleware))
);
return store;
};
const initialState = {
formEditor: {
form: {},
originalFormName: null,
isDirty: false,
isProcessing: false,
isLoading: false,
error: null,
},
};
it('Ensures that fetchForm correctly loads an existing form', async () => {
const store = configureStore(initialState);
await store.dispatch(actions.fetchForm('b3c108be-91b5-4c12-b350-1b8e6b5027c3'));
const state = store.getState().formEditor;
expect(state.form.steps).toHaveLength(1);
expect(state.form.steps[0].id).toBe('f68d89dd-af8f-4e77-af5a-cce6123af91b');
expect(state.isDirty).toBeFalsy();
expect(state.isLoading).toBeFalsy();
expect(state.originalFormName).toBe('Test Form');
expect(state.error).toBeNull();
});
所以,这一切都按预期进行。现在我想做的事情与我对 JSX 组件所做的相同,即监视内部调度。我通常会使用这样的代码:
const spy = jest.spyOn(store, 'dispatch');
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith({
type: 'ADD_QUESTION',
payload: {
questionId: 'b2f78606-18fa-417c-97ca-09f126029ae8'
}
});
一切都按预期进行。但是对于我的新 Action Creator,它不起作用。
My Action Creators 通常首先调用 REQUEST
操作,然后对端点进行异步调用,如果成功则调用 SUCCESS
操作,否则调用 FAILURE
操作。因此,在致电 Action Creator 之后,我希望这是真的:
expect(spy).toHaveBeenCalledTimes(2);
但它似乎总是只被调用一次。我想知道这是不是因为 spy
不记得所有被调用的调度,而只记得最后一个。
关于如何使用实际商店测试 Action Creators 的任何建议将不胜感激!