URLSearchParams 的玩笑测试用例

VYS*_*VYS 4 javascript dom reactjs jestjs


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

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

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

  if(productId){
  this.props.changeId(productId);
}
Run Code Online (Sandbox Code Playgroud)

sli*_*wp2 6

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

\n\n

例如\n index.ts

\n\n
export function main() {\n  console.log(window.location.search);\n  const urlParams = new URLSearchParams(window.location.search);\n  return urlParams.get(\'productId\');\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

index.test.ts:

\n\n
import { main } from \'./\';\n\ndescribe(\'60959971\', () => {\n  it(\'should pass\', () => {\n    const location = {\n      ...window.location,\n      search: \'?productId=1234\',\n    };\n    Object.defineProperty(window, \'location\', {\n      writable: true,\n      value: location,\n    });\n    const actual = main();\n    expect(actual).toBe(\'1234\');\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
 PASS  stackoverflow/60959971/index.test.ts (12.89s)\n  60959971\n    \xe2\x9c\x93 should pass (34ms)\n\n  console.log stackoverflow/60959971/index.ts:129\n    ?productId=1234\n\n----------|---------|----------|---------|---------|-------------------\nFile      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n----------|---------|----------|---------|---------|-------------------\nAll files |     100 |      100 |     100 |     100 |                   \n index.ts |     100 |      100 |     100 |     100 |                   \n----------|---------|----------|---------|---------|-------------------\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        15.136s\n
Run Code Online (Sandbox Code Playgroud)\n

  • 这可行,但最后如何让事情恢复正常呢?我的模拟在其他测试中仍然存在! (2认同)