这是我想测试的一个类:
//Request.js
import axios, {AxiosInstance} from 'axios';
import config from './config';
const axiosSingleton: AxiosInstance = axios.create({
baseURL: 'http://localhost:8080',
});
export default class Request {
public async get<$ResponseType = any>(url: string): Promise<void> {
const response = await axiosSingleton.get(url);
return response.data;
}
}
当我尝试通过创建测试文件来测试这一点时,我不确定如何模拟 axios。我尝试了很多方法,包括间谍和自动模拟。但它们似乎不起作用。这是测试文件的一个版本,我不明白为什么它不起作用
// Request.test.js
import axios from 'axios';
import Request from './Request';
interface ITestResponseDataType {
value: string
}
jest.mock('axios');
describe('Request Tests', () => {
it('should call axios get with the right relativeUrl', async () => {
const getMock = jest.fn();
axios.create.mockReturnValue({
get: getMock
});
getMock.mockResolvedValue({
value: 'value'
});
const data = await new Request().get<ITestResponseDataType>('/testUrl');
expect(getMock.mock.calls.length).toEqual(1);
expect(data).toEqual({
value: 'value'
});
});
});
当我尝试运行测试时出现的错误是 -
TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
src/common/api/Request.test.ts:15:18 - error TS2339: Property 'mockReturnValue' does not exist on type '(config?: AxiosRequestConfig | undefined) => AxiosInstance'.
15 axios.create.mockReturnValue({
这个错误是有道理的,因为 axios 中为 axios.create 定义的类型不应该允许在 .create 上调用 .mockReturnValue。那么我如何告诉 typescript jest 已经进入并修改了它呢?
将模拟方法转换为jest.Mock
, ie
import axios from "axios"
import Request from "./Request";
// Create an Axios mock
// Don't worry about the order, Jest will hoist this above the imports
// See https://jestjs.io/docs/manual-mocks#using-with-es-module-imports
jest.mock("axios", () => ({
create: jest.fn()
}))
// Customise the `create` mock method
(axios.create as jest.Mock).mockReturnValue({
get: getMock
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)