Skip to content

Commit

Permalink
Merge pull request haixiangyan#8 from haixiangyan/feature/new-mock-lo…
Browse files Browse the repository at this point in the history
…cation-method

feat: 添加 Mock location 的新方法
  • Loading branch information
haixiangyan authored May 26, 2022
2 parents 0a45f14 + 45d4c90 commit cee943a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
32 changes: 31 additions & 1 deletion docs/basic/navigation/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,37 @@ Object.defineProperty(window.location, 'href', {
});
```

**答案是:不行!** 你会得到这样的报错:`Error: Not implemented: navigation (except hash changes)`,毕竟是 Hack 手法,并不推荐。
**答案是:不行!** 你会得到这样的报错:`Error: Not implemented: navigation (except hash changes)`,毕竟是 Hack 手法,并不推荐,[详见这个 Issue](https://github.com/facebook/jest/issues/890#issuecomment-501260238)

::: tip
经 Issue 区提醒,也可以尝试以下方法:
```ts
describe('getSearchObj', () => {
it('可以获取当前网址的查询参数对象', () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'https://google.com?a=1&b=2', search: '?a=1&b=2' },
});
expect(window.location.search).toEqual('?a=1&b=2');
expect(getSearchObj()).toEqual({
a: '1',
b: '2',
});
});
it('空参数返回空', () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'https://google.com', search: '' },
});
expect(window.location.search).toEqual('');
expect(getSearchObj()).toEqual({});
});
});
```

这个方法与上面不同点在于:Mock `window.location` 对象,而不是 `window.location.href` 属性。但缺点是不仅要在 `href` 写查询参数,还要在 `search` 再写一遍查询参数。
:::


终于,有人受不了,不就 `jest` 没有把 `jsdom` 对象丢到全局么?把 `jsdom` 测试环境做个扩展不就好了:

Expand Down
2 changes: 1 addition & 1 deletion docs/basic/test-environment/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 测试环境

刚刚的 `sum` 实在是太简单了,根本无难度。这一章我们来搞点有难度。
刚刚的 `sum` 实在是太简单了,根本没难度。这一章我们来搞点有难度。

在很多时候,我们前端的代码往往只在浏览器里运行,经常要用到浏览器的 API。我之前就封装过一个 `storage` 文件,
通过指定 `type = 'indexedDB' | 'cookie' | 'localStorage'` 来切换存储的方式,而且还可以生成自定义的 `key`,防止全局污染。
Expand Down

0 comments on commit cee943a

Please sign in to comment.