Cannot simulate user type in Input using Jest unit test. fireEvent, userEvent do not work
Asked Answered
B

2

5

I have an input field and wish to stimulate the type-in during a unit test. Tried all the methods recommended on internet but still no luck, here is my code:

// In component
<div className="input-area">
                    <div className="subtitle">Put your answer here</div>
                    <Input onChange={({detail}) => onInputChange(detail.value)}
                           value={name}  data-testid="add-input"/>
                </div>
    

// In test
    test("the input field should take user's input", async () => {
        render(<testModal />);
        const inputMessage = screen.getByTestId("add-input");
        inputMessage.focus(); // take this line off has no effect
        await userEvent.keyboard("testTyping");
    
        expect(inputMessage).toHaveValue("testTyping");
    });

Also tried using fireEvent.change and userEvent.type but no luck. The error is Expected the element to have value: testTyping Received: undefined Appreciate any help!

Bodgie answered 5/8, 2022 at 18:13 Comment(0)
T
7

From the doc keyboard(text, options):

You should use userEvent.keyboard if you want to just simulate pressing buttons on the keyboard. You should use userEvent.type if you just want to conveniently insert some text into an input field or textarea.

Try:

import React from 'react'
import {render, screen} from '@testing-library/react'
import userEvent from '@testing-library/user-event'

test("the input field should take user's input", async () => {
  render(<testModal />);
  await userEvent.type(screen.getByTestId("add-input"), 'testTyping');
  expect(inputMessage).toHaveValue("testTyping");
})
Terrilynterrine answered 8/8, 2022 at 2:29 Comment(0)
H
0

I wanted to test if input validation error is triggering after onChange but fireEvent.change did not do the job for me.

Thanks to answer by @lin-du I was able to trigger the error using userEvent. But still don't understand how fireEvent.change do it, since i'm handling the error with onChange in my component.

  it('shows error if input is greater than 50', async () => {
  const user = userEvent.setup();
  const { getByTestId, getByText } = render(<TestComponent />);
  const inputElem = getByTestId('input-test-id');
  await user.type(inputElem, '51');
  const errorText = getByText('value must be less than 50.');
  expect(errorText).toBeTruthy();
});
Harbison answered 16/2, 2024 at 18:13 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.