首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调试玩笑模拟

调试玩笑模拟
EN

Stack Overflow用户
提问于 2022-05-10 19:48:21
回答 1查看 288关注 0票数 1

我有个库在我的玩笑测试中给我添麻烦了。

这个库包含在我的整个项目中,它有一个annoyingFunction,其中包含一个console.error。因此,每当我运行一个测试,我自然会得到不想要的console.error消息到处都是。

我不想模拟整个库,只想模仿annoyingFunction,所以我把它放在我的安装文件中:

代码语言:javascript
复制
jest.mock('myLibrary', () => ({
   ...jest.requireActual('myLibrary'),
   annoyingFunction: jest.fn(),
}));

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

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-10 21:03:06

可能有一些错误,但我的猜测是,annoyingFunction是在库内部调用的。请考虑下面的示例,它没有执行您可能期望的操作:

foo.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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);
  });
});

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

Or...you可以为您提供问题的测试的jest.spyOn console.error,以及之后重新设置间谍

代码语言:javascript
复制
const consoleErrorSpy = jest.spyOn(console, "error");
//...do your test...
consoleErrorSpy.mockRestore();

希望这能帮上忙!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72192180

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档