Javascript 为什么即使Window.location.href包含查询字符串,Window.location.search仍未定义?

Javascript 为什么即使Window.location.href包含查询字符串,Window.location.search仍未定义?,javascript,jestjs,jsdom,Javascript,Jestjs,Jsdom,我编写了一个函数,根据David Walsh的方法获取给定查询字符串的值 export const getQueryStringValue=name=>{ 常量formattedName=name.replace/[\[]/,'\\['.replace/[\]]/,'\\]'; const regex=new RegExp`[\\?&]${formattedName}=[^&]*`; const results=regex.execwindow.location.search; 返回结果===n

我编写了一个函数,根据David Walsh的方法获取给定查询字符串的值

export const getQueryStringValue=name=>{ 常量formattedName=name.replace/[\[]/,'\\['.replace/[\]]/,'\\]'; const regex=new RegExp`[\\?&]${formattedName}=[^&]*`; const results=regex.execwindow.location.search; 返回结果===null ? :decodeURIComponentresults[1]。替换/\+/g'; }; 我已经为基于的函数编写了一个测试

它'应该返回查询字符串值',=>{ global.window=Object.createwindow; Object.definePropertywindow,“位置”{ 价值:{ href:'http://dummy.com?foo=bar' } }; expectgetQueryStringValue'foo'。为'bar'; }; 但是,当我运行测试时,我得到以下错误

expectreceived.toBeexpected//Object.is相等 预期:酒吧 收到: 当我控制台log window.location.search时,它返回undefined


为什么Window.location.href包含查询字符串时,Window.location.search返回未定义?foo=bar?设置href还不够吗?

设置Window.location href时,Window.location搜索不会自动模拟,因为。您有几个选项可以解决此错误

选项1:设置Window.location搜索 它'应该返回查询字符串值',=>{ global.window=Object.createwindow; Object.definePropertywindow,“位置”{ 价值:{ 搜索:“?foo=bar” } }; expectgetQueryStringValue'foo'。为'bar'; }; 选项2:将Window.location设置为新实例 它'应该返回查询字符串值',=>{ global.window=Object.createwindow; Object.definePropertywindow,“位置”{ 值:新URL'http://dummy.com/?foo=bar' }; expectgetQueryStringValue'foo'。为'bar'; };
来源:

这可能是因为在define属性中,该值是一个仅包含href的对象,因此搜索属性为undefined@HaibraynGonz这是有道理的。这让我想知道:当页面加载时,浏览器如何设置window.location.search?为什么失败?你的嘲笑是错误的。你只是在设置href,它不会自动设置其他定位方法。我不知道为什么,因为它没有被模仿。。。。您并不是免费获得所有属性的。@epascarello,因为它没有被模仿。。。。并不是所有的属性都是免费的。这回答了我的问题。我已经相应地更新了我的答案。我在那里发布了一个应该对你有帮助的答案:@kaido我已经根据你的链接更新了我的答案。谢谢你的回答。事实上,我更喜欢这个答案。
  console.log __tests__/getQueryStringValue.test.js:14
    undefined