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.
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:Advanced
You can also mock Location methods that you might need, which don't exist on the URL interface:
You can try:
Have a look at the Jest Issue for that problem:
Jest Issue
The best is probably to create a new
URL
instance, so that it parses your string likelocation.href
does, and so it updates all the properties oflocation
like.hash
,.search
,.protocol
etc.https://repl.it/repls/VoluminousHauntingFunctions
Solution for 2019 from GitHub:
Can rewrite window.location by delete this global in every test.
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: