【问题标题】:jest test case for URLSearchParamsURLSearchParams 的笑话测试用例
【发布时间】:2020-07-12 13:24:20
【问题描述】:

搜索看起来像这样搜索:“?productId=1234”并且changeId 是操作

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

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

  if(productId){
  this.props.changeId(productId);
}

【问题讨论】:

    标签: javascript reactjs dom jestjs


    【解决方案1】:

    困难的部分是如何将模拟值设置为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
    

    【讨论】:

    • 这行得通,但是最后你如何让事情恢复正常呢?我的模拟在其他测试中持续存在!
    【解决方案2】:

    包含 jest.resetModules() 就可以了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 2019-07-06
      • 2018-08-09
      • 2019-09-06
      • 2019-04-15
      • 2019-09-23
      • 2019-07-05
      相关资源
      最近更新 更多