我想用Jest模拟异步函数的catch块中的返回值
这是我正在为其编写单元测试的功能:
try {
make some axios request
}
return users;
} catch (err) {
return new Map();
}
};
it('should catch error when query is unsuccessful', async () => {
axios.get.mockRejectedValue(new Map());
const res = getUserDataByIds('someUserIds');
await expect(res).rejects.toThrow();
});
我从Jest那里得到了错误:
expect(received).rejects.toEqual()
Received promise resolved instead of rejected
Resolved to value: Map {}
我希望测试能够通过,因为我正在模拟一个被拒绝的值。
答案 0 :(得分:2)
这是解决方案:
LONG
:
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
覆盖率100%的单元测试结果:
import { getUserDataByIds } from './';
import axios from 'axios';
jest.mock('axios');
describe('getUserDataByIds', () => {
afterEach(() => {
jest.resetAllMocks();
});
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');
});
});
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58273544