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解决方案。
答案 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!
});
})