4

I'm using "@testing-library/user-event": "^14.2.0" with Next.js 12.

Here is my test

it('test search input', async () => {
    const searchInput = screen.getByPlaceholderText('Search assets');
    expect(searchInput).toBeInTheDocument();

    await userEvent.type(searchInput, 'test{Enter}');
    expect(searchInput).toHaveValue('test');

Test fails with below error

expect(element).toHaveValue(test)

    Expected the element to have value:
      test
    Received:
      t

      195 |
      196 |     await userEvent.type(searchInput, 'test{Enter}');
    > 197 |     expect(searchInput).toHaveValue('test');
          |                         ^
      198 |   });
      199 | });
      200 |

UPDATE: Here is my component code. Component is very simple with an input box with onKeyDown event.

const SearchBox = () => {
      const router = useRouter();
      const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
        const element = event.currentTarget as HTMLInputElement;
        const searchText = element.value;
        if (event.key === 'Enter') {
          router.push({
            pathname: '/search',
            query: { q: searchText },
          });
        }
      };
      return (
        <>
               <input
                className={styles.searchInput}
                type="text"
                placeholder="Search assets"
                onKeyDown={handleKeyDown}
              />
        </>
      );
    };
    
    export default SearchBox;

Can someone please help?

anv
  • 81
  • 1
  • 6
  • Can you add the `component` code that you are tryng to test and also the complete test code? Without that we cant reproduce your code... – Luis Paulo Pinto May 25 '22 at 02:21
  • added component code – anv May 26 '22 at 21:19
  • Did you added you complete test code? Are you mocking `useRouter`? I've tried to simulate your issue but its not possible with the test code you posted. – Luis Paulo Pinto May 26 '22 at 21:40
  • Yes, I have mocked useRouter. As you see, it is executing the test without any useRouter errors but not recognizing entire text. It just takes the first letter as onKeyDown is fired for every key. Were you able to successfully test onKeyDown on an input and assert that input box has the typed text without useRouter? – anv May 27 '22 at 04:20
  • Yes, the test pass successfully for me. The only difference is that I commented the `userRouter` code from component. – Luis Paulo Pinto May 27 '22 at 11:51

1 Answers1

0

You can import waitFor from RTL and then use it later to verify the values entered.

import { screen, waitFor } from "@testing-library/react";



const inputField = screen.getByLabelText(label);
userEvent.type(inputField, data);
await waitFor(() => expect(inputField).toHaveValue(data));
paraS elixiR
  • 1,866
  • 1
  • 18
  • 26