javascript - 如何禁用特定测试的笑话模拟?
问题描述
我为 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()
仍然涉及模拟。
解决方案
您执行的模拟风格是全局模拟。本质上使用“axios”实例的所有测试都硬连线以返回 500 响应。要实现每个测试行为,您需要在测试中本地模拟“axios”。然后,您可以在每个测试中修复您的模拟,以便以您期望的方式响应。
推荐阅读
- elasticsearch - 在elasticsearch中匹配两个字符串数组
- amazon-web-services - AWS 放大 cli 的初始化问题
- nativescript-vue - 从库和刷新库中删除媒体
- sql - 在更新触发器之前,为每个更新更新列
- mongodb - MongoDB:使用字段值作为字段名
- repast-simphony - Repast:在批处理运行期间抑制错误
- r - 如何将 facet_wrap(~list) 与列表一起使用?
- python - 如何计算匹配的特征数量?
- javascript - 使用 getBoundingClientRect() 数据重新定位项目
- reactjs - 在 useEffect 依赖项中使用 localstorage 有效,但会发出警告