【发布时间】:2019-07-13 15:54:13
【问题描述】:
我正在为我的 redux 操作编写测试。在我的一个复杂动作中,我有一个功能,例如aRandomFunction 我想嘲笑。如何添加编写一个模拟 fetchAction 内部使用的函数的测试?谢谢!你可以看下面的例子。
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
jest.mock('../../api/handleError');
jest.mock('../../api/handleResponse');
let store;
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
beforeEach(() => {
store = mockStore({});
fetchMock.restore();
});
const aRandomAction = () => ({
type: "RANDOM_ACTION",
})
const aRandomFunction = (data, dispatch) => {
if (data.isTrue) {
dispatch(aRandomAction);
}
};
export const fetchAction = () => {
return (dispatch) => {
dispatch(requestAction());
return fetch('sampleApi/foo')
.then(response => handleResponse(response))
.then((json) => {
aRandomFunction(json.data, dispatch);
dispatch(receiveAction(json.data));
})
.catch(error => handleError(error));
};
};
describe('testing the fetch Action', () => {
test('testing the fetch action', () => {
const expectedActions = [
{ type: "REQUEST_ACTION" },
{ type: "RECEIVE_ACTION", data: "payload" },
];
return store.dispatch(fetchAction()).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
});
【问题讨论】:
-
你能举例说明
aRandomFunction的来源吗?是从其他文件导入的吗? -
@fmoliveira,使用内联函数更新。
标签: javascript reactjs redux jestjs redux-thunk