Categories
JavaScript Answers

How to mock window.location.href with Jest and Vuejs?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *