javascript - 笑话:如何为文件中的某些测试撤消全局模拟
问题描述
我想为某些测试模拟 Math.random 并将其原始实现用于其他测试。我怎样才能做到这一点?我已经阅读了关于使用jest.doMock
and的内容jest.dontMock
,但是我在使用它们时遇到了一些问题,例如:
- 我似乎需要
require
为了使用doMock
anddontMock
,但我的项目只使用 ES6 模块来导入模块 - 这些函数在接收全局模块(如
Math
. 尝试使用时出现错误jest.doMock("Math.random")
,导致Cannot find module 'Math' from 'app.test.js'
我不一定需要使用doMock
anddontMock
来进行我的测试。它们似乎是我在笑话文档中能找到的最接近我想要实现的东西。但我对替代解决方案持开放态度。
我想在 app.js 中测试我的功能...
export function getRandomId(max) {
if (!Number.isInteger(max) || max <= 0) {
throw new TypeError("Max is an invalid type");
}
return Math.floor(Math.random() * totalNumPeople) + 1;
}
在 app.test.js 里面...
describe("getRandomId", () => {
const max = 10;
Math.random = jest.fn();
test("Minimum value for an ID is 1", () => {
Math.mockImplementationOnce(() => 0);
const id = app.getRandomId(max);
expect(id).toBeGreaterThanOrEqual(1);
});
test("Error thrown for invalid argument", () => {
// I want to use the original implementation of Math.random here
expect(() => getRandomId("invalid")).toThrow();
})
});
解决方案
尝试这个:
describe("getRandomId", () => {
const max = 10;
let randomMock;
beforeEach(() => {
randomMock = jest.spyOn(global.Math, 'random');
});
test("Minimum value for an ID is 1", () => {
randomMock.mockReturnValue(0);
const id = getRandomId(max);
expect(id).toBeGreaterThanOrEqual(1);
});
test("Error thrown for invalid argument", () => {
// I want to use the original implementation of Math.random here
randomMock.mockRestore(); // restores the original (non-mocked) implementation
expect(() => getRandomId("invalid")).toThrow();
})
});
推荐阅读
- c++ - 两个数的对称配对函数
- swift - Swift 无法检索子节点 firebase 数据库
- asp.net-core - Microsoft 标识脚手架页面的 css 文件在哪里?
- django - Django RadioSelect 字段未正确呈现
- javascript - 从 GSI 获取项目但得到“提供的关键元素与架构不匹配”
- node.js - 动态更改 socket.io 来源
- menu - Vuetify - 收听 v-menu 激活器?
- shader - 我是否需要将着色器制服放入 Vertex 函数签名中?
- vba - 如何检查与所有详细信息选项以外的共享日历上的约会?
- powerbi - 将数据加载到 Analysis Services 模型时出现问题