Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get input value (react-testing library)

Can't seem to get the value of an input using react-testing library, but for some reason one can set a value via fireEvent. nameInput is an actual input element

test('verify name validation works', () => {
    const { getByPlaceholderText, getByTestId, debug } = render(<Home/>)

    const passForm = getByTestId('form')
    const nameInput = getByPlaceholderText('Name');

    fireEvent.change(nameInput, { target: { value: 'TestName' }});
    debug(nameInput.value) // error
})

Update

I have to assert as HTMLInputElement to work as ts inferring it as a generic HTMLElement

expect((nameInput as HTMLInputElement).value)

like image 823
swoopy Avatar asked Aug 02 '26 11:08

swoopy


1 Answers

Instead of using type assertion, you can use generic:

const nameInput = getByPlaceholderText<HTMLInputElement>('Name');
expect(nameInput.value).toBe('Nice!')
like image 199
anolan23 Avatar answered Aug 08 '26 18:08

anolan23