Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用Jest测试url更改_Javascript_Unit Testing_Jestjs - Fatal编程技术网

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');