Skip to content

Commit

Permalink
[test]: useHover
Browse files Browse the repository at this point in the history
  • Loading branch information
wmoooid committed May 28, 2024
1 parent 79e4064 commit 41fa177
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
67 changes: 67 additions & 0 deletions src/hooks/useHover/useHover.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react';

import { useHover } from './useHover';

describe('useHover', () => {
afterEach(cleanup);

const mockRef = {
current: document.createElement('div')
};

it('should return ref and hovering state without target element overload', () => {
const { result } = renderHook(() => useHover({}));
const [ref, hovering] = result.current;

expect(ref.current).toBe(null);
expect(hovering).toBe(false);
});

it('should update hovering state when mouse enters and leaves the target', () => {
const { result } = renderHook(() => useHover(mockRef));

expect(result.current).toBe(false);

act(() => fireEvent.mouseEnter(mockRef.current));
expect(result.current).toBe(true);

act(() => fireEvent.mouseLeave(mockRef.current));
expect(result.current).toBe(false);
});

it('should call onEntry and onLeave callback functions when provided', () => {
const onEntry = vi.fn();
const onLeave = vi.fn();

renderHook(() => useHover(mockRef, { onEntry, onLeave }));

act(() => fireEvent.mouseEnter(mockRef.current));
expect(onEntry).toHaveBeenCalledTimes(1);

act(() => fireEvent.mouseLeave(mockRef.current));
expect(onLeave).toHaveBeenCalledTimes(1);
});

it('should work properly without specifying a target element overload', () => {
const MockComponent = () => {
const [ref, isHovering] = useHover({});

return (
<div data-testid='target' ref={ref as React.RefObject<HTMLDivElement>}>
{isHovering ? 'true' : 'false'}
</div>
);
};

render(<MockComponent />);
const target = screen.getByTestId('target');

expect(target).toHaveTextContent('false');

fireEvent.mouseEnter(target);
expect(target).toHaveTextContent('true');

fireEvent.mouseLeave(target);
expect(target).toHaveTextContent('false');
});
});
2 changes: 1 addition & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config';

export default defineConfig({
test: {
include: ['**/*.test.ts'],
include: ['**/*.test.ts', '**/*.test.tsx'],
globals: true,
setupFiles: './tests/setupTests.ts',
environment: 'jsdom',
Expand Down

0 comments on commit 41fa177

Please sign in to comment.