首页 > 解决方案 > 笑话:如何为文件中的某些测试撤消全局模拟

问题描述

我想为某些测试模拟 Math.random 并将其原始实现用于其他测试。我怎样才能做到这一点?我已经阅读了关于使用jest.doMockand的内容jest.dontMock,但是我在使用它们时遇到了一些问题,例如:

我不一定需要使用doMockanddontMock来进行我的测试。它们似乎是我在笑话文档中能找到的最接近我想要实现的东西。但我对替代解决方案持开放态度。

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

标签: javascriptjestjs

解决方案


尝试这个:

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

推荐阅读