Skip to content

Commit

Permalink
test: πŸ’ add useSearchParam tests
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Sep 1, 2019
1 parent b7ad911 commit 481e807
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/__tests__/useSearchParam.test.ts
Original file line number Diff line number Diff line change
@@ -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;
});

0 comments on commit 481e807

Please sign in to comment.