From 481e807e39e53200e54186f8deb18fd6b446b0fd Mon Sep 17 00:00:00 2001 From: streamich Date: Sun, 1 Sep 2019 23:04:51 +0200 Subject: [PATCH] =?UTF-8?q?test:=20=F0=9F=92=8D=20add=20useSearchParam=20t?= =?UTF-8?q?ests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/__tests__/useSearchParam.test.ts | 51 ++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/__tests__/useSearchParam.test.ts diff --git a/src/__tests__/useSearchParam.test.ts b/src/__tests__/useSearchParam.test.ts new file mode 100644 index 00000000..006a2bb7 --- /dev/null +++ b/src/__tests__/useSearchParam.test.ts @@ -0,0 +1,51 @@ +import { act, renderHook } from '@testing-library/react-hooks'; +import useSearchParam from '../useSearchParam'; + +(global as any).window = Object.create(window); +const location = { + search: 'foo=bar&baz=quux', +}; +Object.defineProperty(window, 'location', { + value: location, +}); + +it('returns current location.search value', () => { + location.search = 'foo=bar&baz=quux'; + + const { result } = renderHook(() => useSearchParam('foo')); + + expect(result.current).toBe('bar'); +}); + +it('returns null if search param not found', () => { + location.search = 'foo=bar&baz=quux'; + + const { result } = renderHook(() => useSearchParam('foo2')); + + expect(result.current).toBe(null); +}); + +it('tracks the latest search param value', () => { + location.search = '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(() => { + location.search = 'foo=1&baz=2'; + callback(); + }); + + expect(result.current).toBe('2'); + + window.addEventListener = window$addEventListener; +});