Testing components

Ephe
2 min readFeb 16, 2022

Testing is useful; it reduces the potential for bugs, and it ensures prop/component consistency.

Tests run in a test runner, e.g., Jest.

Jest can test anything you pass to it, but it will need helpers, such as React Testing Library.

Here is an example of a test:

import { screen } from '@testing-library/react';
import React from 'react';
import { renderWithTheme } from '../../helpers/test-utils';
import Input from '../input';
import FormField from './FormField';

const props = {
label: 'FIELD_LABEL',
input: <Input value="VALUE_FIELD" onChange={() => null} />,
};

describe('FormField', () => {
it('renders input with label', () => {
renderWithTheme(<FormField {...props} />); expect(screen.getByLabelText('FIELD_LABEL')).toHaveValue('VALUE_FIELD');
});

it('renders required field', () => {
renderWithTheme(<FormField required {...props} />);
expect(screen.getByLabelText(/field.+\*/i)).toHaveValue('VALUE_FIELD');
});
});

renderWithTheme -> React Testing Library.

it, describe and expect -> Jest.

This test looks at a FormField component in my app. It’s testing my input and label props.

To run the test, I inputted the following code into the terminal:

yarn workspace @ra/web test

The returned test results: -

PASS  src/components/form-field/FormField.test.tsx
PASS src/components/button/Button.test.tsx
PASS src/components/container/Container.test.tsx

Test Suites: 3 passed, 3 total
Tests: 6 passed, 6 total
Snapshots: 0 total
Time: 6.092 s
Ran all test suites.

What you include, and exclude, is up to you, but remember: if a test fails, you may need to look at the component and the test.

Sometimes, you might be testing for something you want to fail. Alternatively, you might be testing to check whether a prop renders with the appropriate theme.

This is a simple test. Event Handling and Custom Hooks can also be tested, but this is not something I’ve tried yet.

>:-)

--

--