get input value (react-testing library)
Asked Answered
S

2

7

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)

Southport answered 14/3, 2021 at 9:13 Comment(4)
Is it a controlled input ? otherwise the change will not really update the input value.Ignace
@GabrielePetrioli it does update the input value, my problem is - I'm not able to get the value from the inputSouthport
@Southport To clarify, is your update the solution to your problem? Or are you still having an issue?Catadromous
I'd suggest you add the update as an answer to this question then. Makes it clear for people landing here that the issue already has a solution.Catadromous
O
4

Instead of using type assertion, you can use generic:

const nameInput = getByPlaceholderText<HTMLInputElement>('Name');
expect(nameInput.value).toBe('Nice!')
Onceover answered 21/8, 2022 at 0:37 Comment(0)
S
3

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

expect((nameInput as HTMLInputElement).value)

Southport answered 14/3, 2021 at 11:13 Comment(1)
A solution without a type assertion would be nice. Type assertions can be dangerous.Euchology

© 2022 - 2024 — McMap. All rights reserved.