Sitemap
Matthew Holman

Matthew Holman

Testing URL Hash / Query with Jest

2 min readApr 28, 2018
Press enter or click to view image in full size

I’m developing part of an application that utilizes query strings to enable deep linking within a certain React component. I needed to test that the hash was correctly parsed and the view was correctly updated.

When a user selects certain options that affect the view, the application updates the url hash with a query string. An example URL with query string hash may be:

http://myapp.com/user/list?limit=25&offset=2&filterQuery=Matthew

The application utilizes ‘parse’ from the qs library to parse the query. It then does some analysis on the query and updates the state based on the result. I had never tested any part of the URL before in my unit tests, so my first step was to make sure I could access the correct area of the DOM and set the query. I added a console.log() to my first test, to make sure the hash was being updated:

const newUrl = 'list?limit=25&offset=2&filterQuery=Matt';Object.defineProperty(window.location, 'hash', {
writable: true,
value: newUrl
});
console.log(window.location.hash);

By using the console.log and running the test, I was able to verify the hash was indeed set as expected.

Get Matthew Holman’s stories in your inbox

Join Medium for free to get updates from this writer.

Next, I ran an instance of the parsing method and checked that the state was updated as expected. The full test looked like:

it('Parses URL params and correctly updates the state', () => {  const wrapper = shallow(
<MyComponent {...props1} />
).first().shallow();
const newUrl = 'list?limit=25&offset=2&filterQuery=Matt'; Object.defineProperty(window.location, 'hash', {
writable: true,
value: newUrl
});
wrapper.instance().parseHash();
expect(wrapper.state().pagination.limit).to.equal(25);
expect(wrapper.state().pagination.offset).to.equal(2);
expect(wrapper.state().filter.filterQuery).to.equal('Matt');
});

It worked! There isn’t anything too complex in the unit test above, but I had never tested URL params before and wanted to share my experience with you.

--

--