Sometimes, we want to mock window.location.href with Jest and Vue.js.
In this article, we’ll look at how to mock window.location.href with Jest and Vue.js.
How to mock window.location.href with Jest and Vue.js?
To mock window.location.href with Jest and Vue.js, we can mock the window.location
property with our own values.
For instance, we write
global.window = Object.create(window);
const url = "https://example.com";
Object.defineProperty(window, "location", {
value: {
href: url,
},
});
expect(window.location.href).toEqual(url);
to call Object.defineProperty
with window
and 'location'
and an object with the value.href
property to set window.location.href
‘s value to the url
.
We make a copy of window
and assign it to global.window
with
global.window = Object.create(window)
Conclusion
To mock window.location.href with Jest and Vue.js, we can mock the window.location
property with our own values.