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:
JavaScript
x
8
1
export const FeedbackForm = ({ closeFunc }) => {
2
const [response, setResponse] = useState(false)
3
const [name, changeName] = useState('')
4
const [email, changeEmail] = useState('')
5
const [feedback, changeFeedback] = useState('')
6
const [patching, setPatching] = useState(false)
7
const emailRegex = /^[w-.]+@([w-]+.)+[w-]{2,4}$/g
8
…
JavaScript
1
12
12
1
<TextField
2
id='name'
3
label='Name'
4
defaultValue={name}
5
onChange={(event) => {
6
changeName(event.target.value)
7
}}
8
disabled={patching}
9
valid={name !== ''}
10
warning='Name cannot be blank.'
11
/>
12
Below is the test I’m running:
JavaScript
1
14
14
1
test('should validate the name field', () => {
2
const wrapper = shallow(<FeedbackForm />)
3
const textField = wrapper.findWhere((el) => el.type() === TextField && el.props().id === 'name')
4
expect((textField).prop('valid')).toBe(false)
5
textField.props().onChange({
6
target: {
7
name: 'changeName',
8
value: 'Dude Man',
9
},
10
})
11
console.log(wrapper.debug())
12
expect((textField).prop('valid')).toBe(true)
13
})
14
The output of console.log(wrapper.debug())
is the following:
JavaScript
1
3
1
<form onSubmit={[Function: handleSubmit]} noValidate={true}>
2
<TextField id="name" label="Name" defaultValue="Dude Man" onChange={[Function: onChange]} disabled={false} valid={true} warning="Name cannot be blank." />
3
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