调试笑话模拟

Debugging jest mocks

我有一个库在我的玩笑测试中给我带来了一些麻烦。

这个库包含在我的整个项目中,它有一个 annoyingFunction,里面有一个 console.error。因此,每当我 运行 进行测试时,我自然会到处收到不需要的 console.error 消息。

我不想模拟整个库,只模拟 annoyingFunction,所以我将它放在我的设置文件中:

jest.mock('myLibrary', () => ({
   ...jest.requireActual('myLibrary'),
   annoyingFunction: jest.fn(),
}));

这正在 运行,但是,原始 annoyingFunction 仍在被调用,console.error 调用污染了我的测试。

如果我控制台记录我的模拟,我清楚地看到 annoyingFunction: [Function: mockConstructor],所以模拟正在工作,但由于某种原因,库中的原始函数仍在被调用。

我在这里错过了什么?我的模拟初始设置有问题吗?

可能有几处错误,但我的猜测是 annoyingFunction 是在库内部调用的。考虑以下示例,它不会执行您可能期望的操作:

foo.js

function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

function multiply(a, b) {
  let total = 0;
  for (let i = 0; i < b; i++) {
    total = add(total, a);
  }
  return total;
}

export {
  add,
  subtract,
  multiply
};

foo_test.js

import * as Operations from "./foo.js";

jest.mock("./foo.js", () => ({
  ...jest.requireActual("./foo.js"),
  add: () => -999,
}));

describe("all the things", () => {
  // Here, the mock does what you would expect, because you're calling the
  // exported function "add."
  it("can add", () => {
    expect(Operations.add(1, 2)).toEqual(-999);
  });
  it("can subtract", () => {
    expect(Operations.subtract(1, 2)).toEqual(-1);
  });
  // Here, the mock doesn't do what you would expect. because unbeknownst to
  // you, `multiply` calls `add` _within_ the module code.  The mock has no
  // effect in this case.
  it("can multiply", () => {
    expect(Operations.multiply(1, 2)).toEqual(2);
  });
});

我不太确定你能做些什么,除了模拟库的导出方法直到你能控制结果。

或者...您可以 jest.spyOn console.error 为任何给您带来问题的测试,并且 reset the spy afterward.

const consoleErrorSpy = jest.spyOn(console, "error");
//...do your test...
consoleErrorSpy.mockRestore();

希望对您有所帮助!