问题描述
这是我想测试的课程:
//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.我尝试了很多方法,包括 - spyOn 和自动模拟.但它们似乎不起作用.这是测试文件的一个版本,我不明白为什么它不起作用
when I try testing this by creating a test file, I am not sure how to mock axios. I tried a bunch of ways including - spyOn and automatic mocking. But they don't seem to work. Here's a version of the test file I am not understanding why it doesn't work
// 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'
});
});
});
尝试运行测试时出现的错误是 -
The error I get when I try running the test is -
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.那么我如何告诉打字稿玩笑已经进入并修改了它?
This error makes sense, because the type defined in axios for axios.create should not allow .mockReturnValue to be called on .create. So how do I tell typescript that jest has gone in and modified it?
推荐答案
Cast the mock method to jest.Mock
,即
Cast the mock method to 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
})
这篇关于Typescript Jest 说我希望模拟的类型不存在 mock 或 mockReturnedValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!