Unit Testing
Learning Test-Driven Development
What is Test-Driven Development?
Testing refers to writing tests for our code to ensure it works properly. There are many kinds of testing in development:
- Unit Testing - Testing single functions
- Component Testing - Testing component functionality
- Endpoint Testing - Testing endpoints(Postman does this)
- End to End Testing - Simulates a users interaction
What is Jest?
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.
Working with Jest
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
What Matchers can I use?
Jest comes with LOTS of matchers. Some you may use commonly are:
- toBe - set a hardcoded value
- toBeTruthy - checks for truthy value
- toContain - checks contents of an array
- toBeNaN - checks for Not a Number value
- not - flips any matcher to check the opposite(similar to the ! operator in JavaScript
Component Testing
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.
Component Testing
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
Simulating Events
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
Copy of Unit Testing/Component Testing
By Cole Finlayson
Copy of Unit Testing/Component Testing
- 145