首页 > 解决方案 > 如何禁用特定测试的笑话模拟?

问题描述

我为 Axios 创建了一个工作模拟:

// __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()仍然涉及模拟。

标签: javascriptunit-testingaxiosjestjs

解决方案


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


推荐阅读