【问题标题】:Jest mock the window.open开玩笑地模拟 window.open
【发布时间】:2019-11-06 20:51:57
【问题描述】:

我如何用玩笑来模拟 window.open? 我尝试了几个选项,但每个选项都失败了

我需要检查是否调用了 window.open 并且应该使用某些参数调用它

假设我有这样的东西

open(): void {
  window.open('/link');
}

【问题讨论】:

  • 请考虑您尝试过的选项以及您遇到的问题。
  • Error: Not implemented: window.open Error: Matcher error: received value must be a mock or spy function

标签: angular unit-testing jestjs


【解决方案1】:

安装这些包:

jest-environment-jsdom
jest-environment-jsdom-global

在您的笑话配置中添加"testEnvironment": "jest-environment-jsdom-global"

假设你有这样一个函数:

open() {
  window.open("abc");
}

然后在测试文件里面:

it("should open the url in window", () => {
  const openSpy =  jest.spyOn(window, "open");

  open();

  expect(openSpy).toHaveBeenCalledTimes(1);
  expect(openSpy).toHaveBeenCalledWith("abc");
});

【讨论】:

  • 它不起作用,您的测试正在使用节点运行并且您没有任何window 那里
  • 添加了您需要添加以使其正常工作的配置。
猜你喜欢
  • 2017-07-01
  • 2023-03-08
  • 2020-03-05
  • 1970-01-01
  • 2019-03-23
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多