【问题标题】:How to test post calls in axios with jest and axios-mock-adapter如何使用 jest 和 axios-mock-adapter 在 axios 中测试 post 调用
【发布时间】:2017-07-14 10:14:34
【问题描述】:

我有这个动作需要测试

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 来调度操作。

这是我迄今为止尝试过的,但它总是说我无法读取未定义的属性“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.");
        });
    });

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

【问题讨论】:

    标签: reactjs redux react-redux jestjs axios


    【解决方案1】:

    尝试从您的 Axios.post 调用中返回承诺,这将通过实例化调用返回:

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

    【讨论】:

      猜你喜欢
      • 2018-06-13
      • 2018-12-18
      • 2018-03-17
      • 2020-11-24
      • 1970-01-01
      • 2021-08-02
      • 2017-12-14
      • 2021-06-04
      • 2021-09-16
      相关资源
      最近更新 更多