javascript 如何使用 Jest 测试 url 更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50977862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test url change with Jest
提问by Kiss
I have the following function to test
我有以下功能要测试
function tradePage() {
setTimeout(function() {
window.location.pathname = document
.getElementById('button')
.getAttribute('new-page');
}, 100);
}
And I've written the following test:
我编写了以下测试:
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"
Things I've already done/tried
我已经做过/尝试过的事情
- 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', });
- 我的packages.json 已经
"testURL"设置好了。 我找到了这个可能的解决方案(没有用):
Object.defineProperty(window.location, 'pathname', { writable: true, value: '/page/myExample/test', });
Any ideas what else I can try?
任何想法我还能尝试什么?
回答by Kiss
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');
That worked fine.
那工作得很好。
回答by Mist
Object.assign(location, { host: "www.newhost.com", pathname: 'file.txt' });
It will update all the locationURL object properties (origin, href, hostname, host).
它将更新所有locationURL 对象属性 ( origin, href, hostname, host)。
so the final hrefproperty will be https://www.newhost.com/file.txt.
所以最终的href属性将是https://www.newhost.com/file.txt.
Do this in a beforeEachblock.
在beforeEach块中执行此操作。
just call console.log(location)to verify the results. Happy coding!
只需打电话console.log(location)验证结果。快乐编码!

