如何使用Jest模拟JavaScript窗口对象? [英] How can I mock the JavaScript window object using Jest?

查看:98
本文介绍了如何使用Jest模拟JavaScript窗口对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试一个在浏览器中打开新标签页的功能

I need to test a function which opens a new tab in the browser

openStatementsReport(contactIds) {
  window.open(`a_url_${contactIds}`);
}

我想模拟窗口的open函数,以便验证传递给open函数的正确URL.

I would like to mock the window's open function so I can verify the correct URL is passed in to the open function.

使用Jest,我不知道如何模拟window.我试图用模拟功能设置window.open,但是这种方式不起作用.下面是测试用例

Using Jest, I don't know how to mock the window. I tried to set window.open with a mock function but this way doesn't work. Below is the test case

it('correct url is called', () => {
  window.open = jest.fn();
  statementService.openStatementsReport(111);
  expect(window.open).toBeCalled();
});

但这给了我错误

expect(jest.fn())[.not].toBeCalled()

jest.fn() value must be a mock function or spy.
    Received:
      function: [Function anonymous]

我应该对测试用例做什么?

What should I do to the test case?

推荐答案

代替window使用global

it('correct url is called', () => {
  global.open = jest.fn();
  statementService.openStatementsReport(111);
  expect(global.open).toBeCalled();
});

您也可以尝试

const open = jest.fn()
Object.defineProperty(window, 'open', open);

这篇关于如何使用Jest模拟JavaScript窗口对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆