Testing refers to writing tests for our code to ensure it works properly. There are many kinds of testing in development:
Jest is a Unit-testing library that comes 'out of the box' with create-react-app. This means you will NOT have to install anything to create unit tests.
Jest is useful when testing functions. In order to do this, Jest syntax lets you organize tests and then use matchers to test for certain outcomes.
const {sum, sayHello} = require('../functions');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1,2)).toBe(3);
})
import functions to test
create a test and label it
pass the function to be tested into expect
pass the function to be tested into expect
use a matcher to define the expected result
Jest comes with LOTS of matchers. Some you may use commonly are:
When working in a library or framework that uses components, it is important to use component testing.
Component testing simulates a component when mounted on the screen, and is particularly useful when checking state values or the results of events.
Component tests are done with Facebooks native React testing library, which is also provided by create-react-app.
import React from 'react';
import {render} from '@testing-library/react';
import Header from '../Components/Header';
it('Does not show dropdown when mounted', () => {
const {queryByTestId} = render(<Header />);
const dropdown = queryByTestId('dropdown');
expect(dropdown).not.toBeTruthy();
})
Component Testing involves simulating parts of a component being in the viewport. To do this you can use the render method:
import render
queryByTestId allows you to grab certain elements in the component to test
use matchers to test
import React from 'react';
import {render, fireEvent} from '@testing-library/react';
import Header from '../Components/Header';
it('Shows dropdown when hamburger is clicked', () => {
const { container, getByTestId } = render(<Header />)
const hamburger = getByTestId('hamburger-button')
fireEvent.click(hamburger)
expect(container.textContent).toContain('Dropdown menu')
})
Component testing also involves testing the results of events. This is done with the fireEvent method.
import fireEvent
choose the event to test by chaining to fireEvent
use matchers to test