Last updated: November 26, 2024
Use the following guidelines when writing a unit test for forms pages.
import { expect } from 'chai';
import { render, screen } from '@testing-library/react';
import { DefinitionTester } from 'platform/testing/unit/schemaform-utils';
describe('MyForm FormID', () => {
const {
schema,
uiSchema,
arrayPath,
} = formConfig.chapters.myFormChapter.pages.myFormPage;
it('renders the form with the correct number of inputs', () => {
render(
<DefinitionTester
arrayPath={arrayPath}
pagePerItemIndex={0}
definitions={formConfig.defaultDefinitions}
schema={schema}
data={initialData}
formData={initialData}
uiSchema={uiSchema}
/>,
);
expect(screen.getAllByRole('combobox')).to.have.lengthOf(6);
expect(screen.getAllByRole('textbox')).to.have.lengthOf(4);
});
});
-
Organize forms config tests by page.
-
Use
<DefinitionTester />to render form configs for testing. -
Test at least the following:
-
Number of each type of input is rendered (example above)
-
Any conditional display logic on the page
-
All field level validation errors
-
When working with RTL, you can use its native functions for filling out form data:
-
fireEvent.change()- simulates user interaction with an input field, but trades the realism of a user input for faster test resolution
test('fills data in a field', () => {
render(<DefinitionTester />);
const selectElement = screen.getByLabelText(/blah/i);
fireEvent.change(selectElement, { target: { value: 'USA' } });
expect(selectElement.value).toBe('USA');
});
-
userEvent.type()- works largely the same as fireEvent.change(), but more accurately approximates real user behavior with a component
test('fills data in a field', async () => {
render(<DefinitionTester />);
const selectElement = screen.getByLabelText(/blah/i);
await userEvent.type(selectElement, 'USA');
expect(selectElement.value).toBe('USA');
});
Help and feedback
-
Get help from the Platform Support Team in Slack.
-
Submit a feature idea to the Platform.