如何解决axios内部功能的承诺和间谍

时间:2019-03-20 09:46:43

标签: javascript promise jestjs axios-mock-adapter

function getusers(config){
     const {successCB} = config;
     return axios.get(url, params)
      .then(response => {
        successCB(response.data, config);
      });
}

************************ UT ******************************

const mock = new MockAdapter(axios);
const successCB = jest.fn();

mock.onGet(url).reply(200, 'success');
const axiosSpy = jest.spyOn(axios, 'get');
const successCBSpy = jest.spyOn(config, 'successCB');

getUsers({successCB});

axiosSpy是下面代码中的成功

expect(axiosSpy).toHaveBeenCalled();

但是要解决成功CB的结果并不能解决问题

expect(successCBSpy).toHaveBeenCalled();

抛出错误为:successCB从未调用

我在做错什么,在这里我应该期待什么?

我只能使用ES6解决方案。

1 个答案:

答案 0 :(得分:1)

请确保您从Promise返回了getusers,以便可以在测试中await

这是一个完整的工作示例:

const axios = require('axios');
const MockAdapter = require('axios-mock-adapter');

const url = 'test-url';
const params = {};

function getusers(config) {
  const { successCB } = config;
  return axios.get(url, params)  // <= return the Promise
    .then(response => {
      successCB(response.data, config);
    });
}

test('getusers', async () => {  // <= async test function
  const mock = new MockAdapter(axios);
  const successCB = jest.fn();

  mock.onGet(url).reply(200, 'success');
  const axiosSpy = jest.spyOn(axios, 'get');

  await getusers({ successCB });  // <= await the Promise

  expect(axiosSpy).toHaveBeenCalled();  // Success!
  expect(successCB.mock.calls[0][0]).toBe('success');  // Success!
})

更新

如果不是async/await语法,则可以在then回调中进行断言,并从测试中返回结果Promise,以便Jest知道等待它:

test('getusers', () => {
  const mock = new MockAdapter(axios);
  const successCB = jest.fn();

  mock.onGet(url).reply(200, 'success');
  const axiosSpy = jest.spyOn(axios, 'get');

  return getusers({ successCB }).then(() => {
    expect(axiosSpy).toHaveBeenCalled();  // Success!
    expect(successCB.mock.calls[0][0]).toBe('success');  // Success!
  });
})