如何模拟模块中特定功能的实现

时间:2021-07-11 15:24:53

标签: javascript jestjs mocking

我正在尝试模拟由我正在测试的函数 funcA 调用的函数 funcB

import * as utils from "./utils.js";

describe("test", () => {
  test("my test", async () => {
    utils.funcA.mockImplementationOnce(() =>
      Promise.resolve({ mockedValue })
    );
    await utils.funcB();
    expect(...)
  });
})

在我的代码中,funcAfuncB 调用,当我运行测试时,funcA 不会被模拟,而是返回实际的 funcA

我也尝试像这样模拟模块,但它没有改变任何东西。

jest.mock("./utils.js", () => {
  const original = jest.requireActual("./utils.js");
  return {
    ...original,
    funcA: () => { mockedValue},
  };
});

也尝试过这样模拟但得到了相同的结果

jest
  .spyOn(utils, "funcA")
  .mockImplementationOnce(() => Promise.resolve({ mockedValue }));

0 个答案:

没有答案