Sometimes, we want to mock window.location.href with Jest and Vuejs.
In this article, we’ll look at how to mock window.location.href with Jest and Vuejs.
How to mock window.location.href with Jest and Vuejs?
To mock window.location.href with Jest and Vuejs, we can set the propert window.location
property to a value.
For instance, we write
global.window = Object.create(window);
const url = "http://example.com";
Object.defineProperty(window, 'location', {
value: {
href: url
}
});
expect(window.location.href).toEqual(url);
in a test function to set global.window
to a copy of the existing window
object with Object.create
.
Then we add a value to globa.window.location
property and set it to an object with the href
property set to url
with Object.defineProperty
.
As a result, the check for window.location.href
equal to url
in the last line should pass.
Conclusion
To mock window.location.href with Jest and Vuejs, we can set the propert window.location
property to a value.