Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 373
VYS Avatar asked Oct 19 '25 18:10

VYS


1 Answers

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
like image 174
slideshowp2 Avatar answered Oct 22 '25 07:10

slideshowp2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!