Coding task · JavaScript and React course · Module 13: Testing React

Practice: Form with Validation

getByLabelText only works when the label is connected to the field: <label htmlFor="crew-name"> and <input id="crew-name"> (in React we write htmlFor, not for). The test renders the form with a jest.fn() mock as onSubmit (you met mocks in the lesson about Jest) and checks which data it was called with. It also checks that onSubmit is not called when there are errors.

Task

Finish the CrewForm crew recruitment form so that it can be tested with React Testing Library. ___BLANK1___: the Crew member name label points with htmlFor at the id of the text field (crew-name), so the test finds it with getByLabelText('Crew member name'). ___BLANK2___: the name error appears when the name, after trimming spaces from the start and the end, has fewer than 2 characters. ___BLANK3___: the role error appears when no role was chosen (the empty value of the list). The errors have role="alert", and with valid data the form calls onSubmit({ name, role }) with the trimmed name and clears the fields.