【发布时间】:2020-12-21 19:58:14
【问题描述】:
我想为某些测试模拟 Math.random,并将其原始实现用于其他测试。我怎样才能做到这一点?我读过有关使用 jest.doMock 和 jest.dontMock 的信息,但在使用它们时遇到了一些问题,例如:
- 我似乎需要
require才能使用doMock和dontMock,但是 我的项目只使用 ES6 模块来导入模块 - 这些函数在像
Math这样的全局模块中也存在问题。 尝试使用jest.doMock("Math.random")时出现错误, 结果Cannot find module 'Math' from 'app.test.js'
我的测试不一定需要使用doMock 和dontMock。它们似乎是我在笑话文档中能找到的最接近我想要实现的东西。但我对替代解决方案持开放态度。
我想在 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();
})
});
【问题讨论】:
标签: javascript jestjs