尝试测试axios
来电并尝试moxios
包。
"axios": "^0.16.2",
"moxios": "^0.4.0",
在此处找到:https://github.com/axios/moxios
按照这个示例,但我的测试错误出现在moxios.install()
行:
import axios from 'axios'
import moxios from 'moxios'
import sinon from 'sinon'
import { equal } from 'assert'
describe('mocking axios requests', function () {
describe('across entire suite', function () {
beforeEach(function () {
// import and pass your custom axios instance to this method
moxios.install()
})
import axios from 'axios';
import moxios from 'moxios';
import sinon from 'sinon';
import { equal } from 'assert';
const akamaiData = {
name: 'akamai'
};
describe('mocking axios requests', () => {
describe('across entire suite', () => {
beforeEach(() => {
// import and pass your custom axios instance to this method
moxios.install();
});
afterEach(() => {
// import and pass your custom axios instance to this method
moxios.uninstall();
});
it('should stub requests', (done) => {
moxios.stubRequest('/akamai', {
status: 200,
response: {
name: 'akamai'
}
});
// const onFulfilled = sinon.spy();
// axios.get('/akamai').then(onFulfilled);
//
// moxios.wait(() => {
// equal(onFulfilled.getCall(0).args[0], akamaiData);
// done();
// });
});
});
});
我确实在这里找到了这个已关闭的问题,但是修复"将axios
传递到moxios.install(axios)
功能不起作用"
答案 0 :(得分:3)
我遇到了同样的问题。事实证明我在axios.js
文件夹中有一个__mocks__
文件(从另一个模拟axios的尝试中删除)。该模拟文件接管了实际的axios代码 - 但是moxios需要真正的 axios代码才能正常运行。当我从axios.js
文件夹中删除__mocks__
文件时,moxios按宣传方式工作。
答案 1 :(得分:0)
原来我不需要moxios
,在我的测试中我不想进行实际的API调用...只需要确保调用该函数。用测试功能修复它。
import { makeRequest } from 'utils/services';
import { getImages } from './akamai';
global.console = { error: jest.fn() };
jest.mock('utils/services', () => ({
makeRequest: jest.fn(() => Promise.resolve({ data: { foo: 'bar' } }))
}));
describe('Akamai getImages', () => {
it('should make a request when we get images', () => {
getImages();
expect(makeRequest).toHaveBeenCalledWith('/akamai', 'GET');
});
});