I've written a function to get the value of a given query string based on David Walsh's 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, ' '));
};
I've written a test for the function based on 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');
});
However, when I run the test I get the following error.
expect(received).toBe(expected) // Object.is equality
Expected: "bar"
Received: ""
And when I console log window.location.search
it returns undefined
.
console.log __tests__/getQueryStringValue.test.js:14
undefined
Why does Window.location search return undefined
even when Window.location.href includes a query string (?foo=bar
)? Shouldn't setting href be enough?