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)
困难的部分是如何将模拟值设置为window.location.search。
例如\n index.ts:
export function main() {\n console.log(window.location.search);\n const urlParams = new URLSearchParams(window.location.search);\n return urlParams.get(\'productId\');\n}\nRun Code Online (Sandbox Code Playgroud)\n\nindex.test.ts:
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});\nRun Code Online (Sandbox Code Playgroud)\n\n100%覆盖率的单元测试结果:
\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\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
14971 次 |
| 最近记录: |