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

时间:2018-11-09 11:52:41

标签: 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;
  }
}

当我尝试通过创建测试文件进行测试时,我不确定如何模拟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。那么如何告诉打字稿说笑话已经进入并对其进行了修改?

4 个答案:

答案 0 :(得分:2)

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

(<jest.Mock>axios.create).mockReturnValue({
  get: getMock
})

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

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

axios.create = jest.fn();

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

答案 3 :(得分:0)

我用axios-mock-adapter解决了这个问题,对我来说没有任何问题,并且还有助于嵌套调用。

    // 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");
    });

希望能对某人有所帮助。