Jest and URL Mocking
I currently ran into a problem while testing some utility functions on a project. We needed to look at the window location to check query string parameters in order to see if our custom parsing was working correctly. Using our favorite JavaScript testing solution, Jest, the standard way of mocking the URL (until it stopped working) was like so:
Object.defineProperty(window.location, 'href', {
writable: true,
value: 'https://www.somthing.com/test.html?query=true'
});
At some point, this stopped working based on what I believe was an update to the version of jsdom that Jest uses under the hood. For myself, and other developers needing to mock window.location values, this was frustrating. You can see others have had this same problem, as found on the Jest issues board on GitHub.
After searching that thread (and other postings), I finally found this little gem hidden amongst the posts. In your Jest configuration, make sure to set the following:
"testURL": "https://www.somthing.com/test.html"
Then in your beforeEach()
section for your test, change the path as needed by using history.pushState()
.
window.history.pushState({}, 'Test Title', '/test.html?query=true');
Voila! Now you change out your path for any test, without having to override any jsdom configurations as others suggest in the thread mentioned above. Not sure on which thread I found this solution on, but kuddos to the dev that posted it!