javascript - 如何使用 Jest 模拟构造函数状态初始化

标签 javascript node.js unit-testing jestjs axios

node.js 的新手。我正在编写一个包装底层 axios 的 JS API 客户端图书馆。在单元测试中,我使用 Jest 模拟 axios .

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

当我使用 jest.mock('axios') 模拟 axios 依赖项时出现问题 - 当尝试调用 axios.get 时在测试中抛出 TypeError :

TypeError: Cannot read property `get` of undefined

我明白为什么会这样,但我还没有找到一种方法来让我模拟 axios 并且不让客户端字段未定义。除了通过构造函数注入(inject) 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));
    }

  }
};

最佳答案

你需要模拟 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);

});

关于javascript - 如何使用 Jest 模拟构造函数状态初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55188024/

相关文章:

javascript - Regex/A?/g 不匹配多个 A

javascript - 如何在d3中加载json对象后访问它

javascript - 获取API : Only redirect if there is no error in POST form

unit-testing - 如何执行涉及 redis、socket.io 和 nodejs/express 的单元测试?

python - 中断 Python 单元测试时关闭资源

c# - 为什么我在尝试调试 NUNIT 测试时获得此 "NUnit.Framework.SuccessException"?

javascript - Chrome 扩展上下文菜单创建多个子项并且仅在弹出窗口打开时有效

javascript - 提取元素的 HTML

javascript - 对象 "name"未定义,无论我如何选择它

node.js - 有条件地跳过 mongoose 钩子(Hook)函数