2022-06-22 06:25:46 -07:00
|
|
|
import { renderHook, act } from '@testing-library/react-hooks';
|
|
|
|
|
|
|
|
import { useDimensions } from '../useDimensions';
|
|
|
|
|
|
|
|
let listener: ((rect: any) => void) | undefined = undefined;
|
|
|
|
|
|
|
|
(window as any).ResizeObserver = class ResizeObserver {
|
2022-06-22 08:20:29 -07:00
|
|
|
|
2022-07-06 10:10:21 -07:00
|
|
|
constructor(ls: any) {
|
2022-06-22 06:25:46 -07:00
|
|
|
listener = ls;
|
|
|
|
}
|
|
|
|
|
|
|
|
observe() {}
|
|
|
|
disconnect() {}
|
2022-06-22 08:20:29 -07:00
|
|
|
|
2022-06-22 06:25:46 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
describe('useDimensions()', () => {
|
|
|
|
it('defaults to 0', () => {
|
|
|
|
const { result } = renderHook(() => useDimensions());
|
|
|
|
|
|
|
|
act(() => {
|
|
|
|
const div = document.createElement('div');
|
2022-07-18 10:36:56 -07:00
|
|
|
(result.current[1] as any)(div);
|
2022-06-22 06:25:46 -07:00
|
|
|
});
|
|
|
|
|
2022-07-18 10:36:56 -07:00
|
|
|
expect(result.current[2]).toMatchObject({
|
2022-06-22 06:25:46 -07:00
|
|
|
width: 0,
|
|
|
|
height: 0,
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
it('measures the dimensions of a DOM element', () => {
|
|
|
|
const { result } = renderHook(() => useDimensions());
|
|
|
|
|
|
|
|
act(() => {
|
|
|
|
const div = document.createElement('div');
|
2022-07-18 10:36:56 -07:00
|
|
|
(result.current[1] as any)(div);
|
2022-06-22 06:25:46 -07:00
|
|
|
});
|
|
|
|
|
|
|
|
act(() => {
|
|
|
|
listener!([
|
|
|
|
{
|
|
|
|
contentRect: {
|
|
|
|
width: 200,
|
|
|
|
height: 200,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
]);
|
|
|
|
});
|
|
|
|
|
2022-07-18 10:36:56 -07:00
|
|
|
expect(result.current[2]).toMatchObject({
|
2022-06-22 06:25:46 -07:00
|
|
|
width: 200,
|
|
|
|
height: 200,
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
it('disconnects on unmount', () => {
|
|
|
|
const disconnect = jest.fn();
|
|
|
|
(window as any).ResizeObserver = class ResizeObserver {
|
2022-06-22 08:20:29 -07:00
|
|
|
|
2022-06-22 06:25:46 -07:00
|
|
|
observe() {}
|
|
|
|
disconnect() {
|
|
|
|
disconnect();
|
|
|
|
}
|
2022-07-06 10:10:21 -07:00
|
|
|
|
2022-06-22 06:25:46 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
const { result, unmount } = renderHook(() => useDimensions());
|
|
|
|
|
|
|
|
act(() => {
|
|
|
|
const div = document.createElement('div');
|
2022-07-18 10:36:56 -07:00
|
|
|
(result.current[1] as any)(div);
|
2022-06-22 06:25:46 -07:00
|
|
|
});
|
|
|
|
|
|
|
|
expect(disconnect).toHaveBeenCalledTimes(0);
|
|
|
|
unmount();
|
|
|
|
expect(disconnect).toHaveBeenCalledTimes(1);
|
|
|
|
});
|
|
|
|
});
|