I am have a case where my code is using the URL api, created as such:
const _url = new URL(window.location.href);
and used like so:
if (_url.searchParams.get('locale')) {
do something
}
However in my jest tests I get an error:
TypeError: Cannot read property 'get' of undefined
I have tried globally mocking by doing this in my setup file:
global.URL = jest.fn(() => {
return {
searchParams: jest.fn(() => {
return {
get: jest.fn(() => {
return '';
}),
};
}),
};
});
But it doesn't seem to work. Looking at the console logged output of my _url object, it looks like it is missing the searchParam property all together:
URL {
[Symbol(impl)]: URLImpl {
_url: {
scheme: 'http',
username: '',
password: '',
host: 'localhost',
port: null,
path: [Array],
query: null,
fragment: null,
cannotBeABaseURL: false
},
[Symbol(wrapper)]: [Circular]
}
}
What am I doing wrong here?