我正在尝试模拟axios的request方法。但是它抛出错误
it('should execute axios request method once', async () => {
jest.mock('axios');
axios.request.mockImplementation(() =>
Promise.resolve({
data: {}
})
);
const requestObj = {
method: 'GET',
url: 'http://mock.url',
headers: {}
};
await request(requestObj);
expect(axios.request).toHaveBeenCalledTimes(1);
});
request.js
export default async (request, httpService = axios) => {
const { method, data, headers } = request;
let { url } = request;
const token = getLocalstorage('token');
if (token) {
headers.token = token;
}
if (method === 'GET') {
if (data) {
url += `?${serialize(data)}`;
}
}
return httpService
.request({
method,
url,
headers: Object.assign({}, headers),
...(method !== 'GET' && { data })
})
.then(successResponse, error => {
throwHttpError(error);
});
};
答案 0 :(得分:1)
这是基于以下解决方案:
"jest": "^24.8.0",
"ts-jest": "^24.0.2",
"typescript": "^3.5.3"
"axios": "^0.19.0",
request.ts
:
import axios from 'axios';
const serialize = data => data;
const getLocalstorage = key => key;
const successResponse = () => console.log('successResponse');
const throwHttpError = error => new Error(error);
export default async (request, httpService = axios) => {
const { method, data, headers } = request;
let { url } = request;
const token = getLocalstorage('token');
if (token) {
headers.token = token;
}
if (method === 'GET') {
if (data) {
url += `?${serialize(data)}`;
}
}
return httpService
.request({
method,
url,
headers: Object.assign({}, headers),
...(method !== 'GET' && { data })
})
.then(successResponse, error => {
throwHttpError(error);
});
};
单元测试request.spec.ts
import request from './request';
import axios from 'axios';
jest.mock('axios');
describe('request', () => {
it('should execute axios request method once', async () => {
(axios.request as jest.Mock<any, any>).mockResolvedValueOnce({ data: 'mocked data' });
const requestObj = {
method: 'GET',
url: 'http://mock.url',
headers: {}
};
await request(requestObj);
expect(axios.request).toHaveBeenCalledTimes(1);
});
});
单元测试结果:
PASS src/stackoverflow/57353897/request.spec.ts
request
✓ should execute axios request method once (13ms)
console.log src/stackoverflow/57353897/request.ts:4
successResponse
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.637s, estimated 3s