简体   繁体   English

URLSearchParams 的笑话测试用例

[英]jest test case for URLSearchParams


search looks like this search: "?productId=1234" and changeId is action搜索看起来像这样搜索:“?productId=1234”并且 changeId 是 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 .困难的部分是如何将模拟值设置为window.location.search

Eg index.ts :例如index.ts

export function main() {
  console.log(window.location.search);
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get('productId');
}

index.test.ts : 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: 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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