Currently, I am implementing unit test for my project and there is a file that contained window.location.href
.
I want to mock this to test and here is m
You can try:
global.window = Object.create(window);
const url = "http://dummy.com";
Object.defineProperty(window, 'location', {
value: {
href: url
}
});
expect(window.location.href).toEqual(url);
Have a look at the Jest Issue for that problem:
Jest Issue
Solution for 2019 from GitHub:
delete global.window.location; global.window = Object.create(window); global.window.location = { port: '123', protocol: 'http:', hostname: 'localhost', };
Working example with @testing-library/react
in 2020 for window.location.assign:
afterEach(cleanup)
beforeEach(() => {
Object.defineProperty(window, 'location', {
writable: true,
value: { assign: jest.fn() }
})
})
Can rewrite window.location by delete this global in every test.
delete global.window.location;
const href = 'http://localhost:3000';
global.window.location = { href };
Basic
The URL object has a lot of the same functionality as the Location object. In other words, it includes properties such as pathname
, search
, hostname
, etc. So for most cases, you can do the following:
delete window.location
window.location = new URL('https://www.example.com')
Advanced
You can also mock Location methods that you might need, which don't exist on the URL interface:
const location = new URL('https://www.example.com')
location.assign = jest.fn()
location.replace = jest.fn()
location.reload = jest.fn()
delete window.location
window.location = location
Many of the examples provided doesn't mock the properties of the original Location object.
What I do is just replace Location object (window.location) by URL, because URL contains the same properties as Location object like "href", "search", "hash", "host".
Setters and Getters also work exactly like the Location object.
Example:
const realLocation = window.location;
describe('My test', () => {
afterEach(() => {
window.location = realLocation;
});
test('My test func', () => {
// @ts-ignore
delete window.location;
// @ts-ignore
window.location = new URL('http://google.com');
console.log(window.location.href);
// ...
});
});