'jest test case for URLSearchParams
search looks like this search: "?productId=1234" and changeId is action
const urlParams = new URLSearchParams(window.location.search);
const productId = urlParams.get('productId');
if(productId){
this.props.changeId(productId);
}
Solution 1:[1]
The difficult part is how to set the mock value to window.location.search
.
E.g.
index.ts
:
export function main() {
console.log(window.location.search);
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get('productId');
}
index.test.ts
:
import { main } from './';
describe('60959971', () => {
it('should pass', () => {
const location = {
...window.location,
search: '?productId=1234',
};
Object.defineProperty(window, 'location', {
writable: true,
value: location,
});
const actual = main();
expect(actual).toBe('1234');
});
});
unit test results with 100% coverage:
PASS stackoverflow/60959971/index.test.ts (12.89s)
60959971
? should pass (34ms)
console.log stackoverflow/60959971/index.ts:129
?productId=1234
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.136s
Solution 2:[2]
Updated with my solution in 2022 with react, react-router-dom and jest
My jest test is as follows
import { BrowserRouter } from "react-router-dom";
test('My component does change search params', () => {
const getPageParams = () => {
const searchParams = new URLSearchParams(window.location.search);
const index = parseInt(searchParams.get("index"));
const query = searchParams.get("query");
return [index, query];
}
render(
<BrowserRouter>
<MyComponentThatManipulatesSearchParams />
</BrowserRouter>
);
const [actualIndex, actualQuery] = getPageParams();
expect(actualIndex).toBe(1);
expect(actualQuery).toBe("happyhacking");
// as a quick check, you can also log the URL
console.info(window.location.href);
});
Solution 3:[3]
Include jest.resetModules() and it works!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | slideshowp2 |
Solution 2 | Lxrd-AJ |
Solution 3 | VS1928 |