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

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

问题描述

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

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

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

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

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?

推荐答案

以下方法对我有用.这种方法允许我测试一些应该在浏览器和 Node.js 中都可以运行的代码,因为它允许我将 window 设置为 undefined.

The following method worked for me. This approach allowed me to test some code that should work both in the browser and in Node.js, as it allowed me to set window to undefined.

这是使用 Jest 24.8(我相信):

This was with Jest 24.8 (I believe):

let windowSpy;

beforeEach(() => {
  windowSpy = jest.spyOn(window, "window", "get");
});

afterEach(() => {
  windowSpy.mockRestore();
});

it('should return https://example.com', () => {
  windowSpy.mockImplementation(() => ({
    location: {
      origin: "https://example.com"
    }
  }));

  expect(window.location.origin).toEqual("https://example.com");
});

it('should be undefined.', () => {
  windowSpy.mockImplementation(() => undefined);

  expect(window).toBeUndefined();
});

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

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