如何使用jest和axios-mock-adapter

时间:2017-07-14 10:14:34

标签: reactjs redux react-redux jestjs axios

我有这个动作,我必须测试

export function addContractorToJob(values) {
return dispatch => {
    axios.post(`${API_URL}add-contractor`, values)
        .then((job) => {
            if(job) {
                dispatch(sendSuccessMessage(ADD_CONTRACTOR, "You have successfully applied for this job."));
            }
        });
}

}

当我收到通过api添加到数据库的承包商的构造时,使用thunk来发送动作。

这是我到目前为止所尝试的,但它总是说我不能读取未定义的属性'然后'但这就是我测试了许多其他没有使用thunk的调度。

    const middlewares = [thunk];
    const mockStore = configureStore(middlewares);
    const mock = new MockAdapter(axios);

it('should call success message action on successfully adding contractor to job', () => {
        mock.onPost(`${actions.API_URL}add-contractor`).reply(200,
            [{id: 123, jobTitle: 'the job title'}]);

        const store = mockStore();
        store.dispatch(actions.addContractorToJob(1001)).then(() => {
            expect(store.getActions()[0].type).toEqual(actions.ADD_CONTRACTOR);
            expect(store.getActions()[0].payload).toEqual("You have successfully applied for this job.");
        });
    });

有没有人知道我哪里出错了?

1 个答案:

答案 0 :(得分:0)

尝试从Axios.post调用中返回promise,该调用将通过实例化调用将其返回:

return dispatch => {
  return axios.post(`${API_URL}add-contractor`, values)
    .then((job) => {
    ...