简体   繁体   中英

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);
}

The difficult part is how to set the mock value to window.location.search .

Eg 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

包括 jest.resetModules() 并且它有效!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM