Typescript Jest说mock或mockReturnedValue在我想要mock的类型上不存在



这里有一个我想测试的类:

//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和自动嘲讽。但它们似乎不起作用。这是测试文件的一个版本,我不明白为什么它不起的作用

// 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已经进入并修改了它呢?

将mock方法转换为jest.Mock,即

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
})

只是对最高评分答案的补充。我更喜欢在类型转换时保留类型定义。可以重写为

(axios as jest.Mocked<typeof axios>).create.mockReturnValue({
get: getMock
});

您需要将axios.create方法替换为Jest mock函数:

axios.create = jest.fn();

这应该允许您设置它的返回值。

我用axios mock适配器解决了这个问题,对我来说没有任何问题,也有助于嵌套调用。

// src/request.ts
import axios from "axios";
export const axiosCreate = axios.create();
export async function someRequest(){
axiosCreate.get("http://localhost/users");
}
// src/__test__/request.test.ts
import * as request from ".../request";
import MockAdapter from "axios-mock-adapter";
const mock = new MockAdapter(request.axiosCreate);
it("Testing mock", async () => {
mock.onGet("http://locahost/users").reply(200, "ok");
const resp = await request.someRequest();
expect(resp).toEqual("ok");
});

希望能帮助到别人。

import axios from 'axios';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;
beforeEach(() => {
jest.resetAllMocks();
mockedAxios.get.mockResolvedValue({
data: []
});
});

对我来说,只有这样才是axios模拟的功能

此示例适用于不同的库,但任务相似。在将导入强制转换为jest.Mocked<typeof MyImport>之后,我只需要将mock函数分配给它的属性,而不是使用mockReturnValue方法。至少这是一种可行的方法。

import Reactotron from '../../reactotron'
import { makeEnhancers } from './enhancers'
jest.mock('../../reactotron')
const mockReactotron = Reactotron as jest.Mocked<typeof Reactotron>
describe('makeEnhancers', () => {
describe('given Reactotron createEnhancer exists', () => {
beforeEach(() => {
mockReactotron.createEnhancer = jest.fn()
})
it('appends the reactotron enhancer', () => {
const enhancers = makeEnhancers()
expect(enhancers).toHaveLength(1)
})
})
describe('given Reactotron createEnhancer does not exist', () => {
beforeEach(() => {
mockReactotron.createEnhancer = undefined
})
it('does not append the reactotron enhancer', () => {
const enhancers = makeEnhancers()
expect(enhancers).toHaveLength(0)
})
})
})

最新更新