【发布时间】:2020-05-15 12:29:37
【问题描述】:
我编写了一个函数来根据 David Walsh 的 Get Query String Parameters 获取给定查询字符串的值。
export const getQueryStringValue = (name) => {
const formattedName = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
const regex = new RegExp(`[\\?&]${formattedName}=([^&#]*)`);
const results = regex.exec(window.location.search);
return results === null
? ''
: decodeURIComponent(results[1].replace(/\+/g, ' '));
};
我已经为基于How to mock window.location.href with Jest + Vuejs?的函数编写了一个测试。
it('should return query string value', () => {
global.window = Object.create(window);
Object.defineProperty(window, 'location', {
value: {
href: 'http://dummy.com?foo=bar'
}
});
expect(getQueryStringValue('foo')).toBe('bar');
});
但是,当我运行测试时,出现以下错误。
expect(received).toBe(expected) // Object.is equality
Expected: "bar"
Received: ""
当我控制台日志window.location.search 它返回undefined。
console.log __tests__/getQueryStringValue.test.js:14
undefined
为什么即使 Window.location.href 包含查询字符串 (?foo=bar),Window.location 搜索也会返回 undefined?设置href还不够吗?
【问题讨论】:
-
可能是因为define属性中的值是一个只有href的对象,所以search属性是未定义的
-
@HaibraynGonzález 这是有道理的。这让我想知道:当页面加载时,浏览器如何设置
window.location.search? -
为什么会失败?你的模拟是错误的。您只是设置href,它不会自动设置其他位置方法。
标签: javascript jestjs jsdom