react-use/tests/useHash.test.ts
xobotyi b6993a6f95
feat(prettier): make prettier a part of eslint.
Also reduce max line width to 100. And remove `lint:types` step for
commit sequence, it bothers when committing incomplete (wip) changes.
2021-02-01 18:58:55 +03:00

55 lines
1.3 KiB
TypeScript

import { renderHook, act } from '@testing-library/react-hooks';
import { useHash } from '../src/useHash';
(global as any).window = Object.create(window);
let mockHash = '#';
const mockLocation = {};
Object.defineProperty(mockLocation, 'hash', {
get() {
return mockHash;
},
set(newHash) {
mockHash = newHash;
window.dispatchEvent(new HashChangeEvent('hashchange'));
},
});
Object.defineProperty(window, 'location', {
value: mockLocation,
});
beforeEach(() => {
window.location.hash = '#';
});
test('returns current url hash', () => {
window.location.hash = '#abc';
const { result } = renderHook(() => useHash());
const hash = result.current[0];
expect(hash).toBe('#abc');
});
test('returns latest url hash when change the hash with setHash', () => {
const { result } = renderHook(() => useHash());
const hash = result.current[0];
const setHash = result.current[1];
expect(hash).toBe('#');
act(() => {
setHash('#abc');
});
const hash2 = result.current[0];
expect(hash2).toBe('#abc');
});
it('returns latest url hash when change the hash with "hashchange" event', () => {
const { result } = renderHook(() => useHash());
const hash = result.current[0];
expect(hash).toBe('#');
act(() => {
window.location.hash = '#abc';
});
const hash2 = result.current[0];
expect(hash2).toBe('#abc');
});