forked from streamich/react-use
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseSearchParam.test.ts
61 lines (43 loc) · 1.35 KB
/
useSearchParam.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { act, renderHook } from '@testing-library/react-hooks';
import useSearchParam from '../src/useSearchParam';
const { location } = window;
let mockSearch: string;
beforeEach(() => {
delete (window as any).location;
const { search, ...restLocation } = location;
// @ts-ignore
window.location = { ...restLocation };
Object.defineProperty(window.location, 'search', {
get: function () {
return mockSearch;
},
});
});
it('returns current location.search value', () => {
mockSearch = 'foo=bar&baz=quux';
const { result } = renderHook(() => useSearchParam('foo'));
expect(result.current).toBe('bar');
});
it('returns null if search param not found', () => {
mockSearch = 'foo=bar&baz=quux';
const { result } = renderHook(() => useSearchParam('foo2'));
expect(result.current).toBe(null);
});
it('tracks the latest search param value', () => {
mockSearch = 'foo=bar&baz=quux';
let callback;
const window$addEventListener = window.addEventListener;
window.addEventListener = (event, cb) => {
if (event === 'pushstate') {
callback = cb;
}
};
const { result } = renderHook(() => useSearchParam('baz'));
expect(result.current).toBe('quux');
act(() => {
mockSearch = 'foo=1&baz=2';
callback();
});
expect(result.current).toBe('2');
window.addEventListener = window$addEventListener;
});