Skip to content
Advertisement

Unit test with react hook fails

I don’t understand the result I get on this unit test. I expect the second check for textField.valid to be true and instead it returns false.

Below is part of the component I’m testing against:

export const FeedbackForm = ({ closeFunc }) => {
  const [response, setResponse] = useState(false)
  const [name, changeName] = useState('')
  const [email, changeEmail] = useState('')
  const [feedback, changeFeedback] = useState('')
  const [patching, setPatching] = useState(false)
  const emailRegex = /^[w-.]+@([w-]+.)+[w-]{2,4}$/g

 <TextField
    id='name'
    label='Name'
    defaultValue={name}
    onChange={(event) => {
      changeName(event.target.value)
    }}
    disabled={patching}
    valid={name !== ''}
    warning='Name cannot be blank.'
  />

Below is the test I’m running:

  test('should validate the name field', () => {
    const wrapper = shallow(<FeedbackForm />)
    const textField = wrapper.findWhere((el) => el.type() === TextField && el.props().id === 'name')
    expect((textField).prop('valid')).toBe(false)
    textField.props().onChange({
      target: {
        name: 'changeName',
        value: 'Dude Man',
      },
    })
    console.log(wrapper.debug())
    expect((textField).prop('valid')).toBe(true)
  })

The output of console.log(wrapper.debug()) is the following:

<form onSubmit={[Function: handleSubmit]} noValidate={true}>
          <TextField id="name" label="Name" defaultValue="Dude Man" onChange={[Function: onChange]} disabled={false} valid={true} warning="Name cannot be blank." />

So why does the test fail?

Advertisement

Answer

The problem was that I needed to change the declaration to let textField = wrapper.findWhere((el) => el.type() === TextField && el.props().id === 'name') and then redeclare textField

textField = wrapper.findWhere((el) => el.type() === TextField && el.props().id === 'name')

to update the value in the DOM

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement