已经使用 axios 模拟方法创建了单元测试用例,并且确实看到了下面的控制台错误。尝试了很多方法,但都没有解决问题。对 REACT/JEST 社区来说非常新,但会尽力解决这个问题。
期待:
- 包括成功、错误场景在内的所有测试用例都应 100% 覆盖,并且应在没有警告/错误的情况下通过。
- 应使用空结果列表和非空结果列表测试响应。
- 还应处理由于超时/网络引起的错误场景。
错误:
Expected: undefined
Received: {"results": []}
(node:76675) UnhandledPromiseRejectionWarning:
Unhandled promise rejection. This error originated
either by throwing inside of an async function without a catch block,
or by rejecting a promise which was not handled with .catch().
(rejection id: 1)
(node:76675) [DEP0018] DeprecationWarning: Unhandled promise rejections
are deprecated. In the future, promise rejections that are not handled will
terminate the Node.js process with a non-zero exit code.
我尝试了什么:
index.js
export default getAreas = area => axios.get(`/test/areas/${area}`);
__mocks__/axios.js
const axiosMocked = {
get: jest.fn(() => Promise.resolve({ results: [] }))
};
export default axiosMocked;
__tests__/index.test.js
import mockAxios from 'axios';
import getAreas from '../index';
afterEach(() => {
jest.clearAllMocks();
});
it('fetches results from api', () => {
mockAxios.get.mockImplementationOnce(() => Promise.resolve({ results: [] }));
getAreas('atl').then(response => {
expect(response).toEqual();
});
expect(mockAxios.get).toHaveBeenCalledTimes(1);
expect(mockAxios.get).toHaveBeenCalledWith('/test/areas/atl');
});