Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Adds the ability to mock location and history in your unit-tests using mockWindowLocation. (thx @tkrotoff!)
Why?
While we're using
react-router-dom
, there are some situations where its routing components (e.g.Link
,Navigate
, etc) can't (or shouldn't) be used. In those scenarios, we need a way to inspect and evaluate any mutations to window.location between tests, especially since we use HashRouter. Otherwise, your tests may fail with an error similar to the following output:Aren't there already simpler ways to stub out the location in tests?
Yes, but with caveats. You could modify the code to use the
assign
method if it's your own code, but that may not work with any dependencies without monkey patching them. Sometimes you can get away with a function like safelyStubAndThenCleanup or other methods listed on that Jest issue, but I've personally found many of those workarounds to be problematic at best when used with Vitest. mockWindowLocation feels like a more robust and thorough solution that automatically works with both Jest & Vitest without rewriting code.