Ajout test basique de UserForm avec Jest/Enzyme

This commit is contained in:
2020-03-09 13:31:26 +01:00
parent 67732aa00a
commit 4e554d5ef2
5 changed files with 810 additions and 38 deletions

View File

@ -1,4 +1,4 @@
import { useEffect } from 'react';
import React, { useEffect } from 'react';
import { WithForm } from './WithForm';
export function UserForm({ form, onSubmit }) {
@ -59,7 +59,7 @@ export function UserForm({ form, onSubmit }) {
const validators = {
username: (value, formData) => {
if (!value) return { hasError: true, message: 'Le nom d\'utilisateur ne peut pas être vide !' }
if (!value) return { hasError: true, message: 'Le nom d\'utilisateur ne peut être vide !' }
return { hasError: false, message: '' };
},
password: (value, formData) => {

View File

@ -0,0 +1,34 @@
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
import React from 'react';
import { ExtendedUserForm as UserForm } from './UserForm';
describe('<UserForm />', () => {
describe('username validation', () => {
test('empty username', () => {
const onSubmit = formData => console.log(formData);
const form = mount(<UserForm onSubmit={onSubmit} />);
form.find('[name="username"]').simulate('change', { target: { value: '' } });
const props = form.find('UserForm').props();
expect(props.form.errors.username.hasError).toBe(true);
});
test('non empty username', () => {
const onSubmit = formData => console.log(formData);
const form = mount(<UserForm onSubmit={onSubmit} />);
form.find('[name="username"]').simulate('change', { target: { value: 'foo' } });
const props = form.find('UserForm').props();
expect(props.form.errors.username.hasError).toBe(false);
});
});
});

View File

@ -1,3 +1,4 @@
import React from 'react';
import { useState, useEffect } from 'react';
export function WithForm(validators) {
@ -11,7 +12,13 @@ export function WithForm(validators) {
const [ submitted, setSubmitted ] = useState(false);
const validateField = (name) => {
if (typeof validators[name] !== 'function') return;
if (typeof validators[name] !== 'function') {
setFormErrors(formErrors => {
return { ...formErrors, [name]: { hasError: false, message: '' } };
});
return
};
const value = formData[name];
const result = validators[name](value, formData);
setFormErrors(formErrors => {