SearchInput.spec.tsx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { fireEvent, render } from '@testing-library/react';
  2. import SearchInput from '../../customInput/SearchInput';
  3. import { I18nextProvider } from 'react-i18next';
  4. import i18n from '../../../i18n';
  5. import { vi } from 'vitest';
  6. const mockHistoryPushFn = vi.fn();
  7. vi.mock('react-router-dom', () => ({
  8. useHistory: () => ({
  9. push: mockHistoryPushFn,
  10. location: {
  11. search: '',
  12. },
  13. }),
  14. }));
  15. // clear the influence of vi.useFakeTimers
  16. afterEach(() => {
  17. vi.useRealTimers();
  18. });
  19. describe('test search input component', () => {
  20. it('renders default state', () => {
  21. const mockSearchFn = vi.fn();
  22. const container = render(
  23. <I18nextProvider i18n={i18n}>
  24. <SearchInput searchText="search text" onSearch={mockSearchFn} />
  25. </I18nextProvider>
  26. );
  27. // material textfield input role is textbox
  28. expect(container.getByRole('textbox')).toBeInTheDocument();
  29. expect(container.getByRole('textbox')).toHaveValue('search text');
  30. });
  31. it('checks input value change event', () => {
  32. const mockSearchFn = vi.fn();
  33. const container = render(
  34. <I18nextProvider i18n={i18n}>
  35. <SearchInput onSearch={mockSearchFn} />
  36. </I18nextProvider>
  37. );
  38. const input = container.getByRole('textbox');
  39. fireEvent.change(input, { target: { value: 'search change test' } });
  40. expect(input).toHaveValue('search change test');
  41. // mock Enter key press event
  42. fireEvent.keyPress(input, { key: 'Enter', code: 13, charCode: 13 });
  43. expect(mockSearchFn).toBeCalledTimes(1);
  44. // mock clear icon click event
  45. const clearIcon = container.getByTestId('clear-icon');
  46. fireEvent.click(clearIcon);
  47. expect(input).toHaveValue('');
  48. });
  49. it('checks location change according to search value', () => {
  50. const mockSearchFn = vi.fn();
  51. // mock setTimeout
  52. vi.useFakeTimers();
  53. const container = render(
  54. <I18nextProvider i18n={i18n}>
  55. <SearchInput onSearch={mockSearchFn} />
  56. </I18nextProvider>
  57. );
  58. const input = container.getByRole('textbox');
  59. fireEvent.change(input, { target: { value: 'route' } });
  60. expect(mockHistoryPushFn).not.toBeCalled();
  61. // fast-forward until all timers have been executed
  62. vi.runAllTimers();
  63. expect(mockHistoryPushFn).toBeCalled();
  64. expect(mockHistoryPushFn).toBeCalledWith({ search: 'search=route' });
  65. });
  66. });