• Home
  • Speaking
  • Leadership
  • Development
  • About Myself
Menu

Ryan Doll

Software Engineering Manager at RSA Security
  • Home
  • Speaking
  • Leadership
  • Development
  • About Myself
andre-hunter-350301-unsplash.jpg

Jest and URL Mocking

March 29, 2018

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!

In Development Tags Jest, Unit Testing, JavaScript
← Better Call Doll Twitch LivestreamSonarQube With Docker For JavaScript Or TypeScript Projects →
  • Ryan Doll
    The big news of the year for me... https://t.co/3VGzIVIFVH
    Aug 20, 2018, 8:39 PM
  • Ryan Doll
    Anyone have thoughts on https://t.co/0Y6wQHtRRI ? Been using it for a week now on a project... any crazy gotcha's I should be watching for?
    Aug 13, 2018, 8:19 PM
  • Ryan Doll
    I actually have some thoughts on this (considering my current events!). Let's talk about this next Monday night! https://t.co/ektm7T1OpX
    Aug 13, 2018, 8:17 PM
  • Ryan Doll
    RT @unclebobmartin: If one or more of the Agile practices does not work for your team; replace that practice with another that accompli… https://t.co/NKJfdbrzGX
    Aug 11, 2018, 11:15 AM
  • Ryan Doll
    RT @bettercalldoll: Leveling Up and Life... Right now on https://t.co/wgfTRwd4MB
    Aug 6, 2018, 8:28 PM