react-use/tests/useWindowSize.test.tsx
Anton Zinovyev 8de2a3ee13 chore: move tests to top level /tests folder
chore: move all the tests to the separate directory outside of sources;

chore: remove jest.config.js (config moved to the package.json);

test: unused import in test;

test: 💍 fix tests add back x and y to useMeasure

chore: 🤖 add linter to /tests folder

ci: 🎡 limit Jest worker count for CircleCI
2019-11-08 16:55:34 -05:00

89 lines
2.2 KiB
TypeScript

import { act, renderHook } from '@testing-library/react-hooks';
import { replaceRaf } from 'raf-stub';
import useWindowSize from '../useWindowSize';
import { isClient } from '../util';
declare var requestAnimationFrame: {
reset: () => void;
step: (steps?: number, duration?: number) => void;
};
describe('useWindowSize', () => {
beforeAll(() => {
replaceRaf();
});
afterEach(() => {
requestAnimationFrame.reset();
});
it('should be defined', () => {
expect(useWindowSize).toBeDefined();
});
function getHook(...args) {
return renderHook(() => useWindowSize(...args));
}
function triggerResize(dimension: 'width' | 'height', value: number) {
if (dimension === 'width') {
(window.innerWidth as number) = value;
} else if (dimension === 'height') {
(window.innerHeight as number) = value;
}
window.dispatchEvent(new Event('resize'));
}
it('should return current window dimensions', () => {
const hook = getHook();
expect(typeof hook.result.current).toBe('object');
expect(typeof hook.result.current.height).toBe('number');
expect(typeof hook.result.current.width).toBe('number');
});
it('should use passed parameters as initial values in case of non-browser use', () => {
const hook = getHook(1, 1);
expect(hook.result.current.height).toBe(isClient ? window.innerHeight : 1);
expect(hook.result.current.width).toBe(isClient ? window.innerWidth : 1);
});
it('should re-render after height change on closest RAF', () => {
const hook = getHook();
act(() => {
triggerResize('height', 360);
requestAnimationFrame.step();
});
expect(hook.result.current.height).toBe(360);
act(() => {
triggerResize('height', 2048);
requestAnimationFrame.step();
});
expect(hook.result.current.height).toBe(2048);
});
it('should re-render after width change on closest RAF', () => {
const hook = getHook();
act(() => {
triggerResize('width', 360);
requestAnimationFrame.step();
});
expect(hook.result.current.width).toBe(360);
act(() => {
triggerResize('width', 2048);
requestAnimationFrame.step();
});
expect(hook.result.current.width).toBe(2048);
});
});