gpt4 book ai didi

unit-testing - jest redux-thunk 测试是否调度同一模块的操作

转载 作者:行者123 更新时间:2023-12-02 03:51:19 25 4
gpt4 key购买 nike

我正在尝试为 redux 操作创建者编写一个测试,该测试调度在同一文件中定义的另一个操作。这很难解释,所以这是一个例子:

// actions/timer.js

export const onClickButton = () => {
return dispatch => {
// ... do something
dispatch(someAction);
dispatch(onTimerStart()); // This is the action creator stated below
};
};

export const onTimerStart = () => {
return dispatch => {
// ... do something
dispatch(someAction);
};
};

我正在使用 jest,并且我想确保在调用 onClickButton 时调度 onTimerStart 操作。 (在我的实际代码中,这些操作创建者接受一些参数,并根据这些参数,应该或不应该调度 onTimerStart)

我似乎不知道如何模拟 onTimerStart 所以我可以测试它是否被调用。

最佳答案

您可以使用“redux-mock-store ”并断言您的预期操作已被调度,而不是模拟 onTimerStart()。

这是一个粗略的例子。

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as timerActions from './actions/timerActions';
import * as types from './constants/actionTypes';
import { InitialAppState } from './reducers/initialState';

const createMockStore = configureMockStore([thunk]);

describe('timerActions', () => {

it('successful call should dispatch someAction', () => {

// Arrange.
const expectedActions = [
{ type: types.someAction},
];

const store = createMockStore(InitialAppState);

// Act.
store.dispatch(actions.onClickButton());

// Assert.
const dispatchedActions = store.getActions();
expect(dispatchedActions).toEqual(expectedActions);
});

});

使用此示例,您只需添加您提到的参数,然后从正确的位置导入您的 actionCreators、actionTypes 和initialState。

请注意,此示例是用 typescript 编写的。

关于unit-testing - jest redux-thunk 测试是否调度同一模块的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41990330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com