简体   繁体   中英

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.

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.

    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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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