如何使用Jest测试网址更改 [英] How to test url change with Jest
本文介绍了如何使用Jest测试网址更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要测试以下功能
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测试网址更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文