Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: add tests for useKeysPressed #128

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions src/hooks/useKeysPressed/useKeysPressed.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { fireEvent, renderHook } from '@testing-library/react';

import { useKeysPressed } from './useKeysPressed';

describe('Should use keys pressed', () => {
it('Should set only unique keys', () => {
const props = {
enabled: true,
target: document
};
const { result } = renderHook(() => useKeysPressed(props));

fireEvent.keyDown(document, {
key: 'c',
code: 'KeyC'
});
fireEvent.keyDown(document, {
key: 'g',
code: 'KeyG'
});
fireEvent.keyDown(document, {
key: 'c',
code: 'KeyC'
});

expect(result.current).toEqual([
{
key: 'c',
code: 'KeyC'
},
{
key: 'g',
code: 'KeyG'
}
]);
});

it("Shouldn't set keys", () => {
const props = {
enabled: false,
target: document
};
const { result } = renderHook(() => useKeysPressed(props));

fireEvent.keyDown(document, {
key: '2',
code: 'Numpad2'
});
fireEvent.keyDown(document, {
key: '/',
code: 'Slash'
});

expect(result.current).toHaveLength(0);
});

it('Should reset keys after disabling', () => {
const initialProps = {
enabled: true,
target: document
};
const { rerender, result } = renderHook((props) => useKeysPressed(props), {
initialProps
});

fireEvent.keyDown(document, {
key: 'Meta',
code: 'MetaLeft'
});
rerender({
target: document,
enabled: false
});

expect(result.current).toHaveLength(0);
});

it('Should clear keys after keyUp event', () => {
const props = {
enabled: true,
target: document
};
const { result } = renderHook(() => useKeysPressed(props));

fireEvent.keyDown(document, {
key: 'g',
code: 'KeyG'
});
fireEvent.keyUp(document, {
key: 'g',
code: 'KeyG'
});

expect(result.current).toHaveLength(0);
});
});