1 回答

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以創(chuàng)建一個(gè)模擬函數(shù)來(lái)替換axios.get()方法。
index.ts:
import axios from 'axios';
export async function getUserDataByIds(ids: string[]) {
try {
const users = await axios.get('/users');
return users;
} catch (err) {
return new Map();
}
}
index.spec.ts:
import { getUserDataByIds } from './';
import axios from 'axios';
describe('getUserDataByIds', () => {
it('should return empty Map when axios.get failed', async () => {
const getError = new Error('network error');
axios.get = jest.fn().mockRejectedValue(getError);
const actualValue = await getUserDataByIds(['1']);
expect(actualValue).toEqual(new Map());
expect(axios.get).toBeCalledWith('/users');
});
it('should return users', async () => {
const mockedUsers = [{ userId: 1 }];
axios.get = jest.fn().mockResolvedValue(mockedUsers);
const actualValue = await getUserDataByIds(['1']);
expect(actualValue).toEqual(mockedUsers);
expect(axios.get).toBeCalledWith('/users');
});
});
100% 覆蓋率的單元測(cè)試結(jié)果:
PASS src/stackoverflow/58273544/index.spec.ts
getUserDataByIds
? should return empty Map when axios.get failed (12ms)
? should return users (4ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 5.597s, estimated 7s
源代碼:https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58273544
添加回答
舉報(bào)