如何使用Jest模拟JavaScript窗口对象?


104

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

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

我想模拟窗口的open功能,以便验证传递给该open功能的URL是否正确。

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

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]

我应该对测试用例怎么办?任何建议或提示表示赞赏。

Answers:


83

代替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);

3
试过这个但对我不起作用。我的情况很奇怪,模拟在本地有效,但不适用于Travis中的PR合并...有什么想法吗?
Alex JM

@AlexJM您有同样的问题吗?介意分享如何模拟窗口对象?
丹尼

1
我只是在测试中定义window.property
maracuja-juice

@安德烈亚斯有什么办法嘲笑窗口为未定义stackoverflow.com/questions/59173156/...
迪利普·托马斯

谢谢!几个小时后,我只需要改变windowglobal
SrAxi

58

以下是对我有用的方法。这种做法让我来测试一些代码,应在浏览器和节点都工作,因为它让我设置windowundefined

这就是Jest 24.8(我相信):

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();
});

这要好得多,Object.defineProperty因为这样可以在模拟时不影响其他测试。
谢尔盖

10

我们也可以用它定义globalsetupTests

// setupTests.js
global.open = jest.fn()

global在实际测试中使用它来调用它:

// yourtest.test.js
it('correct url is called', () => {
    statementService.openStatementsReport(111);
    expect(global.open).toBeCalled();
});

7

有两种方法可以在Jest中模拟全局变量:

  1. 使用mockImplementation方法(最像玩笑的方式),但是它仅对那些具有的默认实现的变量有效jsdomwindow.open是其中之一:
test('it works', () => {
  // setup
  const mockedOpen = jest.fn();
  // without making a copy you will have a circular dependency problem
  const originalWindow = { ...window };
  const windowSpy = jest.spyOn(global, "window", "get");
  windowSpy.mockImplementation(() => ({
    ...originalWindow, // in case you need other window properties to be in place
    open: mockedOpen
  }));

  // tests
  statementService.openStatementsReport(111)
  expect(mockedOpen).toBeCalled();

  // cleanup
  windowSpy.mockRestore();
});
  1. 将值直接分配给全局属性,最直接的方法是,但是可能会触发某些window变量的错误消息,例如window.href
test('it works', () => {
  // setup
  const mockedOpen = jest.fn();
  const originalOpen = window.open;
  window.open = mockedOpen;

  // tests
  statementService.openStatementsReport(111)
  expect(mockedOpen).toBeCalled();

  // cleanup
  window.open = originalOpen;
});
  1. 不要直接使用全局变量(需要一些重构)

与其直接使用全局值,不如从另一个文件中导入它更清洁,因此使用Jest进行模拟将变得微不足道。

./test.js

jest.mock('./fileWithGlobalValueExported.js');
import { windowOpen } from './fileWithGlobalValueExported.js';
import { statementService } from './testedFile.js';

// tests
test('it works', () => {
  statementService.openStatementsReport(111)
  expect(windowOpen).toBeCalled();
});

./fileWithGlobalValueExported.js

export const windowOpen = window.open;

./testedFile.js

import { windowOpen } from './fileWithGlobalValueExported.js';
export const statementService = {
  openStatementsReport(contactIds) {
    windowOpen(`a_url_${contactIds}`);
  }
}

5

您可以尝试以下方法:

import * as _Window from "jsdom/lib/jsdom/browser/Window";

window.open = jest.fn().mockImplementationOnce(() => {
    return new _Window({ parsingMode: "html" });
});

it("correct url is called", () => {
    statementService.openStatementsReport(111);
    expect(window.open).toHaveBeenCalled();
});


4

我找到了一种简单的方法:删除并替换

describe('Test case', () => {
  const { open } = window;

  beforeAll(() => {
    // Delete the existing
    delete window.open;
    // Replace with the custom value
    window.open = jest.fn();
    // Works for `location` too, eg:
    // window.location = { origin: 'http://localhost:3100' };
  });

  afterAll(() => {
    // Restore original
    window.open = open;
  });

  it('correct url is called', () => {
    statementService.openStatementsReport(111);
    expect(window.open).toBeCalled(); // Happy happy, joy joy
  });
});

3

在我的组件中,我需要访问window.location.search,这是我在玩笑测试中所做的:

Object.defineProperty(global, "window", {
  value: {
    location: {
      search: "test"
    }
  }
});

如果在不同的测试中窗口属性必须不同,我们可以将窗口模拟放入函数中,并使其可写,以覆盖不同的测试:

function mockWindow(search, pathname) {
  Object.defineProperty(global, "window", {
    value: {
      location: {
        search,
        pathname
      }
    },
    writable: true
  });
}

并在每次测试后重置

afterEach(() => {
  delete global.window.location;
});

3

我直接分配jest.fn()window.open

window.open = jest.fn()
// ...code
expect(window.open).toHaveBeenCalledTimes(1)
expect(window.open).toHaveBeenCalledWith('/new-tab','__blank')

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.