29
rated 0 times
[
35]
[
6]
/ answers: 1 / hits: 19890
/ 5 Years ago, wed, march 20, 2019, 12:00:00
I'm not great at testing, and new to Jest and Enzyme. I have a Login component that consists of two TextInput components for username and password and a Button component. I am testing each component individually.
I would just like to test that a username and password was returned by onLogin.
Here is the component:
export const onLogin = (user, password) => {
console.log('User', user, 'Password', password)
return [user, password];
};
function Login() {
const [user, setUser] = useState();
const [password, setPassword] = useState();
return (
<LoginWrapper>
<Branding brand={brand.brandName} />
<FormWrapper onSubmit={(e) => { e.preventDefault(); onLogin(user, password) }}>
<Stack>
<TextInput
className=username
type=text
label=Username
onChange={e => setUser(e.target.value)}
/>
</Stack>
<Stack>
<TextInput
className=password
type=password
label=Password
onChange={e => {setPassword(e.target.value); console.log('user', user)}}
/>
</Stack>
<Stack padding=0 align=right>
<Button type=submit>Login</Button>
</Stack>
</FormWrapper>
</LoginWrapper>
);
}
export default Login;
My test:
describe(<Login />, () => {
it(renders text input correctly, () => {
const tree = renderer.create(<ThemeProvider theme={themes.default}><Login /></ThemeProvider>).toJSON();
expect(tree).toMatchSnapshot();
});
it(calls onLogin when button clicked, () => {
const onSubmitMock = jest.fn();
const component = Enzyme.mount(
<ThemeProvider theme={themes.default}><Login onSubmit={onSubmitMock} /></ThemeProvider>
);
component.find(input.username).simulate('change', { target: { value: 'myUser' } })
component.find(input.password).simulate('change', { target: { value: 'myPassword' } })
component.find(form).simulate(submit);
console.log(onClickMock.mock, onSubmitMock.mock)
expect(onSubmitMock).toBeCalled()
});
});
Results:
Expected mock function to have been called, but it was not called.
More From » reactjs