首页 > 解决方案 > 如何使用 Jest 测试 url 更改

问题描述

我有以下功能要测试

function tradePage() {
  setTimeout(function() {
    window.location.pathname = document
      .getElementById('button')
      .getAttribute('new-page');
  }, 100);
}

我写了以下测试:

test('should change page when button is clicked', () => {
  var button = document.querySelector('#button');

  jest.useFakeTimers();
  button.dispatchEvent(createEvent('click'));
  jest.runAllTimers();

  expect(window.location.pathname).toEqual('/new-url');
});

但是当我运行测试时,我得到了这个错误:

    expect(received).toEqual
    Expected value to equal:
    "/new-url"
    Received:
    "blank"

我已经做过/尝试过的事情

有什么想法我还能尝试吗?

标签: javascriptunit-testingjestjs

解决方案


我通过在测试开始时声明一个全局变量找到了一种工作方法:

global.window = { location: { pathname: null } };

并像这样检查这个变量:

expect(global.window.location.pathname).toEqual('/new-url');

那工作得很好。


推荐阅读