Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 my sample code:

it("method A should work correctly", () => {       const url = "http://dummy.com";       Object.defineProperty(window.location, "href", {         value: url,         writable: true       });       const data = {         id: "123",         name: null       };       window.location.href = url;       wrapper.vm.methodA(data);       expect(window.location.href).toEqual(url);     }); 

But I get this error:

TypeError: Cannot redefine property: href         at Function.defineProperty (<anonymous>) 

I had tried some solutions but not resolve it. I need some hints to help me get out of this trouble. Plz help.

like image 403
Tran Son Hoang Avatar asked Jan 03 '19 11:01

Tran Son Hoang


2 Answers

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

like image 78
mava Avatar answered Sep 16 '22 12:09

mava


2020 Update


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 
like image 24
jabacchetta Avatar answered Sep 18 '22 12:09

jabacchetta