Reputation: 35
i'm trying write test's with Jest and Enzyme on React. But on call .simulate('change')
function the value keep NULL
and don't change to expected value [email protected]
.
My App.jsx:
const App = () => {
const [username, setUsername] = React.useState(null);
const [password, setPassword] = React.useState(null);
const handleChange = (event) => {
setUsername(event.target.value);
};
return (
<div
style={{
height: "100vh",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
<input
type="email"
id="email"
value={username}
onChange={handleChange}
/>
<input
type="password"
id="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
<button>Enviar</button>
</div>
);
};
export default App;
My App.test.js:
import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import {
configure,
shallow,
} from 'enzyme';
import App from '../App';
configure({
adapter: new Adapter()
});
it('<App/> state input', () => {
const email = shallow(<App/>).find('#email');
email.simulate('change', {
target: {
value: '[email protected]'
}
});
expect(email.prop('value')).toEqual('[email protected]');
})
Return error on npm test
command:
Expected: "[email protected]"
Received: null
Upvotes: 0
Views: 4895
Reputation: 455
For those who got multiple inputs just like mine. I had the same issue and found the working solution from wrapper not updated after simulate('change'). #1999
Just add name
or id
to distinguish between being-tested components:
.simulate('change', {target: {name: 'inputFirstName', value: 'value'}})
It took me quite a long time on this, so hope it helps someone here...
Upvotes: 2
Reputation: 134
I just had the same error. Investigating in the link is better explained but basically you have to do a re-find to update the values ...
cont wrapper = shallow(<App/>);
let email = wrapper.find('#email');
email.simulate('change', {
target: {
value: '[email protected]'
}
});
email = wrapper.find('#email');
expect(email.prop('value')).toEqual('[email protected]');
Upvotes: 6