如何使用 Jest 测试 url 更改 [英] How to test url change with Jest

查看:29
本文介绍了如何使用 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');
});

但是当我运行测试时出现此错误:

But when I run the test I get this error:

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

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

  • 我的packages.json 已经设置了"testURL".
  • 我找到了这个可能的解决方案(没有用):

  • My packages.json already have the "testURL" set up.
  • I found this possible solution (that didn't work):

Object.defineProperty(window.location, 'pathname', {
  writable: true,
  value: '/page/myExample/test',
});

还有什么我可以尝试的想法吗?

Any ideas what else I can try?

推荐答案

通过在测试开始时声明一个全局变量,我找到了一个可行的方法:

I found a working method by declaring in the beginning of the test a global variable:

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

并像这样检查这个变量:

and checked this variable like this:

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

效果很好.

这篇关于如何使用 Jest 测试 url 更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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