简体   繁体   English

如何使用玩笑和axios-mock-adapter在axios中测试帖子调用

[英]How to test post calls in axios with jest and axios-mock-adapter

i have this action that i have to test 我有这个动作我必须测试

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."));
            }
        });
}

} }

its using thunk to dispatch an action when i receive a conformation of a contractor being added to the database through an api. 当我收到通过api添加到数据库的承包商的构想时,使用thunk调度操作。

this is what i have tryed so far but it always says that i cannot Cannot read property 'then' of undefined but this is how i have been testing many of my other dispatches that are not using thunk. 到目前为止,这是我一直尝试的结果,但它总是说我无法读取未定义的属性“ then”,但这就是我一直在测试许多其他未使用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.");
        });
    });

does anyone have any idea where i am going wrong at all? 有谁知道我哪里出错了?

try returning the promise from your Axios.post call which will return it back through the instantiating call: 尝试从您的Axios.post调用返回诺言,该诺言将通过实例化调用返回:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM