URLSearchParams的最佳测试用例

问题描述 投票:0回答:1

搜索看起来像这样的搜索:“?productId = 1234”,并且changeId为action

const urlParams = new URLSearchParams(window.location.search);

 const productId = urlParams.get('productId');

  if(productId){
  this.props.changeId(productId);
}
javascript reactjs dom jestjs
1个回答
0
投票

困难的部分是如何将模拟值设置为window.location.search

例如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');
  });
});

具有100%覆盖率的单元测试结果:

 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
© www.soinside.com 2019 - 2024. All rights reserved.