【问题标题】:How can I disable a jest mock for a particular test?如何禁用特定测试的笑话模拟?
【发布时间】:2021-10-30 21:34:53
【问题描述】:

我已经为 Axios 创建了一个可用的 Mock:

// __mocks__/axios.js
// Based on https://jestjs.io/docs/manual-mocks

const axios = jest.createMockFromModule("axios");
const log = console.log.bind(console);

axios.create = () => {
  log(`Running axios.create`);
  return {
    get: () => {
      log(`Running get`);
      return {
        status: 500,
        statusText: "Internal Server Error",
        body: {
          onFire: "Mock API response from mock axios module",
        },
      };
    },
  };
};

module.exports = axios;

这在我的测试中运行良好 - 模拟自动加载并且“抛出错误”测试有效:

describe(`getLatestPrice`, () => {
  it(`throws an error when the response is bad`, async () => {
    expect(() => {
      log(`Should throw`);
      return getLatestPrice(assetCode);
    }).toThrow();
  });

  it(`gets a single price by stream code`, async () => {
    // Disabling the mock isn't working
    jest.unmock("axios");
    const price = await getLatestPrice(assetCode);
    log(`price`, price);
    expect(price).toEqual({
      ...
    });
  });
})

但是第二个测试 - 调用 jest.unmock() - 仍然使用模拟库。

如何禁用单个测试的模拟?

更新:阅读https://github.com/facebook/jest/issues/2649 我也尝试使用requireActual() 覆盖模拟:

const actualAxios = jest.requireActual("axios");
const mockAxios = require("axios");
mockAxios.create = actualAxios.create;

但是对axios.create() 的调用仍然涉及模拟。

【问题讨论】:

标签: javascript unit-testing axios jestjs


【解决方案1】:

您执行的模拟方式是全局模拟。本质上使用“axios”实例的所有测试都硬连线以返回 500 响应。要实现每个测试行为,您需要在测试中本地模拟“axios”。然后,您可以在每个测试中修复您的模拟,以便以您期望的方式响应。

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 2019-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-22
  • 2019-09-23
相关资源
最近更新 更多