我如何用Jest模拟构造函数状态初始化

时间:2019-03-15 17:35:13

标签: javascript node.js unit-testing jestjs axios

node.js的新功能。我正在编写包装基础axios库的JS API客户端。在单元测试中,我使用Jest来模拟axios。

在我的API类的构造函数中,我传入一个URL,并使用axios.create函数来创建axios的自定义实例并将其绑定到client属性。

当我用jest.mock('axios')模拟axios依赖关系时会出现问题-尝试调用axios.get时,在测试中引发了TypeError:

TypeError: Cannot read property `get` of undefined

我知道为什么会这样,但是我还没有找到一种方法来模拟axios并没有使client字段不确定。除了通过构造函数注入axios之外,还有其他方法可以解决此问题吗?

客户端代码并在下面进行测试:


client.js

jest.mock("axios");
const axios = require("axios");
const mockdata = require("./mockdata");
const ApiClient = require("../../../src/clients/apiclient");


const BASE_URL = "https://www.mock.url.com"

const mockAxiosGetWith = mockResponse => {
  axios.get.mockResolvedValue(mockResponse);
};

test("should make one get request",  async () => {
  mockAxiosGetWith(MOCK_RESPONSE)

  // the client field in apiclient is undefined
  // due to the jest module mocking of axios
  const apiclient = new ApiClient.AsyncClient(BASE_URL);


  // TypeError: Cannot read property `get` of undefined
  return await apiclient.get("something").then(response => {
    expect(axios.get).toHaveBeenCalledTimes(1);
  });

});

client.test.js

const axios = require("axios");

const getClient = (baseUrl = null) => {
  const options = {
    baseURL: baseUrl
  };

  const client = axios.create(options);

  return client;
};

module.exports = {
  AsyncClient: class ApiClient {
    constructor(baseUrl = null) {
      this.client = getClient(baseUrl);
    }

    get(url, conf = {}) {
      return this.client
        .get(url, conf)
        .then(response => Promise.resolve(response))
        .catch(error => Promise.reject(error));
    }

  }
};

1 个答案:

答案 0 :(得分:5)

您需要模拟axios,以便它将返回包含create函数的对象,该函数应返回带有get的对象

import axios from 'axios'
jest.mock('axios', () => ({create: jest.fn()}))


test("should make one get request",  async () => {
  const get = jest.fn(()=>Promise.resolve(MOCK_RESPONSE))
  axios.create.mockImplementation(()=>({get}))

  const apiclient = new ApiClient.AsyncClient(BASE_URL);

  await apiclient.get("something")
  expect(get).toHaveBeenCalledTimes(1);

});