我想测试一下在useEffect内部调用了一个redux操作。
我有我的根组件作为-
export default ({ children, initialState = {} }) => {
return (
<Provider store={createStore(reducers, initialState, applyMiddleware(thunk))}>
{children}
</Provider>
);
};
字符串
包裹在组件里的成分-
import { clearState } from '../actions';
const App= (props) => {
useEffect(() => {
props.clearState();
}, []);
return (
<div>
App
</div>
);
};
/**
* Map the state to properties so that the component only
* get relevant data.
*
* @param {object} state The current application state
* @return {object} Data from the state that the component needs
*/
const mapStateToProps = () => {
return {};
};
export default connect(mapStateToProps, {
clearState
})(App);
型
我的clearState操作是-
export const clearState = () => {
return async (dispatch) => {
dispatch({ type: CLEAR_STATE, payload: {} });
};
};
型
我试图测试当App组件加载时,clearState操作被调用。
const mockStore = configureStore([]);
describe('App component', () => {
it('should call clearState action on component mount', () => {
// Create a mock store
const store = mockStore({});
// Create a spy for the clearState action
const clearStateSpy = jest.spyOn({ clearState }, 'clearState');
// Mount the component with the Provider and store
const wrapper = mount(
<Root store={store}>
<App/>
</Root>
);
// Expect the clearState action to have been called
expect(clearStateSpy).toHaveBeenCalled();
});
});
型
但是测试失败了,因为调用的数量返回为0。任何关于我做错了什么的建议都会有很大的帮助。
1条答案
按热度按时间ee7vknir1#
jest.spyOn
向原始方法添加了一个“mock wrapper”,因此您需要将模块作为对象提供给jest.spyOn
,然后在测试期间,组件将使用从提供给spyOn
的模块导入的“mock wrapper”方法。字符串