【发布时间】:2021-01-06 22:10:42
【问题描述】:
我不清楚在使用以下设置时如何模拟我的 api 响应。
我有以下测试:
import React from 'react';
import { cleanup, render, wait } from '@testing-library/react';
import axios from 'axios';
import Condition from './index.jsx';
jest.mock('axios', () => {
return {
create: jest.fn(() => ({
get: jest.fn().mockResolvedValue({ data: {} }),
interceptors: {
request: { use: jest.fn(), eject: jest.fn() },
response: { use: jest.fn(), eject: jest.fn() },
},
})),
};
});
afterEach(cleanup);
test('fetches and displays data', async () => {
axios.get.mockResolvedValue({ data: 'mock data' });
const { container } = render(<Condition {...props} />);
await wait(() => expect(container.textContent).toContain('Current milestone'));
expect(container).toBeDefined();
});
... 以及以下 api 助手:
import axios from 'axios';
const api = axios.create({
baseURL: window.apiPath,
withCredentials: true,
});
api.interceptors.request.use(config => {
const newConfig = Object.assign({}, config);
newConfig.headers.Accept = 'application/json';
return newConfig;
}, error => Promise.reject(error));
export default api;
我的Condition 组件在挂载时使用以下函数来获取数据:
const fetchAsync = async endpoint => {
const result = await api.get(endpoint);
setSuffixOptions(result.data.data);
console.log('result.data.data', result.data.data);
};
测试中的axios.get.mockResolvedValue({ data: 'mock data' });行导致如下错误:
TypeError: Cannot read property 'mockResolvedValue' of undefined
124 |
125 | test('fetches and displays data', async () => {
> 126 | axios.get.mockResolvedValue({ data: 'mock data' });
| ^
127 | const { container } = render(<Condition {...props} />);
128 | await wait(() => expect(container.textContent).toContain('Current milestone'));
129 | expect(container).toBeDefined();
我应该使用不同的方法来模拟响应吗?
编辑
调用axios.create.get.mockResolvedValue({ data: 'mock data' }); 会导致同样的错误。
【问题讨论】:
-
因为你的 Axios 测试替身只有一个 create prop,没有 get。
-
但是create方法是创建api的,它在api文件中有get和interceptors方法。如何为该形状修改
axios.get.mockResolvedValue? -
当然,但是您在测试中没有调用它。
-
调用
axios.create.get.mockResolvedValue({ data: 'mock data' });会导致同样的错误。 -
axios.create.get正在尝试访问get属性 on 函数,它不会调用函数。
标签: javascript reactjs axios jestjs react-testing-library