Typescript Jest说我希望模拟的类型不存在模拟或模拟返回值

Ash*_*man 1 typescript jestjs

这是我要测试的课程:

//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;
  }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试通过创建测试文件进行测试时,我不确定如何模拟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'
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

我尝试运行测试时遇到的错误是-

 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({
Run Code Online (Sandbox Code Playgroud)

该错误是有道理的,因为axios中为axios.create定义的类型不应允许在.create上调用.mockReturnValue。那么如何告诉打字稿说笑话已经进入并修改了呢?

Phi*_*hil 5

将模拟方法转换为jest.Mock,即

(<jest.Mock>axios.create).mockReturnValue({
  get: getMock
})
Run Code Online (Sandbox Code Playgroud)


小智 5

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

(axios as jest.Mocked<typeof axios>).create.mockReturnValue({
  get: getMock
});
Run Code Online (Sandbox Code Playgroud)

  • 对我不起作用: ``` 类型的参数 '{ get: jest.Mock&lt;any, any&gt;; }' 不可分配给“AxiosInstance”类型的参数。输入 '{ get: Mock&lt;any,any&gt;; }' 缺少类型“AxiosInstance”中的以下属性:defaults、拦截器、getUri、request 和 6 more.ts(2345) ``` (2认同)

Gli*_*her 2

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

axios.create = jest.fn();
Run Code Online (Sandbox Code Playgroud)

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