aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/organisms/forms/search-form/search-form.test.tsx
blob: 8b4379b456a7dad173a255149ed27916710ac277 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { describe, expect, it, jest } from '@jest/globals';
import { userEvent } from '@testing-library/user-event';
import type { Ref } from 'react';
import { act, render, screen as rtlScreen } from '../../../../../tests/utils';
import { SearchForm, type SearchFormRef } from './search-form';

describe('SearchForm', () => {
  it('renders a search input with a submit button', () => {
    render(<SearchForm />);

    expect(
      rtlScreen.getByRole('searchbox', { name: 'Search for:' })
    ).toBeInTheDocument();
    expect(
      rtlScreen.getByRole('button', { name: 'Search' })
    ).toBeInTheDocument();
  });

  it('can submit the form', async () => {
    const onSubmit = jest.fn((_search: { query?: string }) => undefined);
    const user = userEvent.setup();
    const query = 'autem voluptatum eos';

    render(<SearchForm onSubmit={onSubmit} />);

    // eslint-disable-next-line @typescript-eslint/no-magic-numbers
    expect.assertions(3);

    expect(onSubmit).not.toHaveBeenCalled();

    await user.type(
      rtlScreen.getByRole('searchbox', { name: 'Search for:' }),
      query
    );
    await user.click(rtlScreen.getByRole('button', { name: 'Search' }));

    expect(onSubmit).toHaveBeenCalledTimes(1);
    expect(onSubmit).toHaveBeenCalledWith({ query });
  });

  it('can give focus to the search input', () => {
    const ref: Ref<SearchFormRef> = { current: null };

    render(<SearchForm ref={ref} />);

    act(() => {
      ref.current?.focus();
    });

    expect(rtlScreen.getByRole('searchbox')).toHaveFocus();
  });
});