Jest:如何撤消文件中某些测试的全局mock



我想为某些测试模拟Math.random,并将其原始实现用于其他测试。我怎样才能做到这一点?我读过关于使用jest.doMockjest.dontMock的文章,但在使用它们时遇到了一些问题,比如:

  • 我似乎需要require才能使用doMockdontMock,但是我的项目仅使用ES6模块导入模块
  • 这些函数在接收像Math这样的全局模块时也存在问题。尝试使用jest.doMock("Math.random")时出错Cannot find module 'Math' from 'app.test.js'中的结果

我的测试不一定需要使用doMockdontMock。它们似乎是我在玩笑文档中能找到的最接近我想要实现的目标的东西。但我对其他解决方案持开放态度。

我想在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();
})
});

最新更新