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)

4
  • Is it a controlled input ? otherwise the change will not really update the input value. Commented Mar 14, 2021 at 9:46
  • @GabrielePetrioli it does update the input value, my problem is - I'm not able to get the value from the input Commented Mar 14, 2021 at 9:47
  • @swoopy To clarify, is your update the solution to your problem? Or are you still having an issue? Commented Mar 14, 2021 at 10:56
  • 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. Commented Mar 14, 2021 at 11:09

2 Answers 2

4

Instead of using type assertion, you can use generic:

const nameInput = getByPlaceholderText<HTMLInputElement>('Name');
expect(nameInput.value).toBe('Nice!')
Sign up to request clarification or add additional context in comments.

Comments

3

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

expect((nameInput as HTMLInputElement).value)

1 Comment

A solution without a type assertion would be nice. Type assertions can be dangerous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.