首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Jest模拟构造函数状态初始化

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

Stack Overflow用户
提问于 2019-03-15 17:35:12
回答 1查看 4.7K关注 0票数 2

对node.js来说是新手。我正在编写一个JS客户机,它封装了底层的axios库。在单元测试中,我使用取笑模拟axios。

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

当我用jest.mock('axios')来模拟axios依赖关系时,问题就出现了--当尝试调用axios.get时,在测试中抛出了一个TypeError。

代码语言:javascript
复制
TypeError: Cannot read property `get` of undefined

我理解为什么会发生这种情况,但我还没有找到一种方法来使我能够模拟axios,并且不需要对客户端字段进行未定义。除了通过构造函数注入axios之外,还有其他方法可以解决这个问题吗?

客户端代码和测试如下:

client.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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));
    }

  }
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-15 19:30:03

您需要模拟axios,这样它将返回一个包含create函数的对象,该对象应该与get一起返回该对象。

代码语言:javascript
复制
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);

});
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55188024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档