3

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!

snowfall
  • 31
  • 3

1 Answers1

4

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");
})
Lin Du
  • 88,126
  • 95
  • 281
  • 483