Hi . Now i'm testing my app with enzyme, jest and typescript.
When i test input in controlled components with simulate function, it is okay if i use static setState method like below.
For example, setState like this should be passed;
onChangeHandler = (e: React.FormEvent<HtmlInputElement>) => {
this.setState({
someStatename : e.target.value
})
}
However when i called setState with abstract key: value type like this....
onChangeHandler = (e: React.FormEvent<HtmlInputElement>) => {
const name = e.target.name;
const value = e.target.value
this.setState({
[name] : value
})
}
it always failed in test, though it's okay in runtime. Both simulating input event with 'input' or 'change' are failed.
Did i make a mistake something???
Have you tried console.log(name) to see if it's what you expect?
Yes. it definitely log what i expect in my console.
i even changed my 'e' type as React.ChangeEvent but it was same.
The type is irrelevant; that's not JS, it's just informing Flow or TypeScript at build time and has no impact on the value at runtime. If you removed all the type information your code would always behave identically.
If 'someStateName' === name, then your example should definitely work. To clarify, the first example passes your tests, and the second fails them?
Yes. first one was passed , second wasn't.
To make things clearly,
my code was..
const input = wrapper.find('input').first(); // which is event target.
//then
input.simulate('input', {
target: { value : someValue}
})
whether i simulate input as 'input' or 'change' , result was same in second test case(which is [name]: value)
(I've edited all your posts to use three backticks, (```jsx) instead of one, so it's properly indented and highlighted - please do so in future posts)
The second argument to simulate is the e that the function receives. You're not providing a name, which is why it's undefined and [name]: doesn't work. A console.log call in your test would have revealed that as well.
Oh, I didn't know 2nd argument of 'simulate' can mock target object. i was so ridiculous.
now , the test passed with code below.
const input = FormWrapper.find('input').first();
const expectedValue = 'someValue';
input.simulate('change', {
target: {
name: 'someName',
value: 'someValue'
}
});
expect(FormWrapper.state().someName).toEqual(expectedValue);
i really appreciate to your help.
Most helpful comment
Oh, I didn't know 2nd argument of 'simulate' can mock target object. i was so ridiculous.
now , the test passed with code below.
i really appreciate to your help.