Javascript 如何使用Jest测试url更改
我有以下功能要测试Javascript 如何使用Jest测试url更改,javascript,unit-testing,jestjs,Javascript,Unit Testing,Jestjs,我有以下功能要测试 函数贸易页(){ setTimeout(函数(){ window.location.pathname=文档 .getElementById('按钮') .getAttribute('new-page'); }, 100); } 我编写了以下测试: test('单击按钮时应更改页面',()=>{ var button=document.querySelector(“#button”); 开玩笑。使用faketimers(); dispatchEvent(createEvent
函数贸易页(){
setTimeout(函数(){
window.location.pathname=文档
.getElementById('按钮')
.getAttribute('new-page');
}, 100);
}
我编写了以下测试:
test('单击按钮时应更改页面',()=>{
var button=document.querySelector(“#button”);
开玩笑。使用faketimers();
dispatchEvent(createEvent('click'));
jest.runAllTimers();
expect(window.location.pathname).toEqual('/newurl');
});
但是当我运行测试时,我得到了以下错误:
expect(received).toEqual
Expected value to equal:
"/new-url"
Received:
"blank"
我已经做过/尝试过的事情
- mypackages.json已经设置了
“testURL”
- 我找到了这个可能的解决方案(不起作用):
你知道我还能尝试什么吗?我在测试开始时声明了一个全局变量,从而找到了一个有效的方法:
global.window = { location: { pathname: null } };
然后像这样检查这个变量:
expect(global.window.location.pathname).toEqual('/new-url');
这很好。Object.assign(位置,{host:“www.newhost.com”,路径名:'file.txt'});
它将更新所有位置
URL对象属性(来源、href、主机名、主机
)
因此,最后的href
属性将是https://www.newhost.com/file.txt
在每个块之前的中执行此操作
只需调用console.log(location)
即可验证结果。快乐编码
expect(global.window.location.pathname).toEqual('/new-url');