我有一个API实用函数,它使用构造函数表示法调用axios:
axios({
method,
url: `${BASE_URL}/${url}`,
data
});我想用Jest来模拟这一点,但不太确定是怎么做的。我只能模拟特定的axios函数(get、post等)。
有谁有这样使用axios时嘲笑它的例子吗?
发布于 2020-01-23 19:01:30
您可以使用jest.mock(moduleName, factory, options)模拟axios函数。
例如。
index.js
import axios from 'axios';
export function main() {
const BASE_URL = 'https://stackoverflow.com';
const url = 'api';
const data = {};
return axios({
method: 'GET',
url: `${BASE_URL}/${url}`,
data,
});
}index.test.js
import { main } from '.';
import axios from 'axios';
jest.mock('axios', () => jest.fn());
describe('59873406', () => {
it('should pass', async () => {
const mResponse = { data: 'mock data' };
axios.mockResolvedValueOnce(mResponse);
const response = await main();
expect(response).toEqual(mResponse);
expect(axios).toBeCalledWith({ method: 'GET', url: 'https://stackoverflow.com/api', data: {} });
});
});100%覆盖的单元测试结果:
PASS src/stackoverflow/59873406/index.test.js
59873406
✓ should pass (7ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.362s, estimated 13s源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59873406
https://stackoverflow.com/questions/59873406
复制相似问题