Basic Testing
Configure Libraries
Let's start by configuring enzyme (because jest is built into create-react-app):
import Enzyme from 'enzyme'
import EnzymeAdapter from 'enzyme-adapter-react-16'
Enzyme.configure({ adapter: new EnzymeAdapter() })Pro tip: To save time, you can move this configuration into its own file and tell jest to run it before every jest test. In create-react-app, a designated src/setupTests.js is already set up for this.
Writing Tests
Empty Critical Tests
Start by writing out empty tests for all the critical parts of your app: features that, if they were changed, you'd want to be warned.
// This app shows a counter and a button that, when clicked, increments the counter
test('renders without error', () => {}) // <= PRO TIP: this is an excellent basic first test
test('renders increment button', () => {})
test('renders counter display', () => {})
test('counter starts at 0', () => {})
test('pressing button increments counter display', () => {})
// ^ This last test focuses on *BEHAVIOUR* by looking at output on page, not statedata-test attribute
Pro tip: One effective method to test whether a component renders is to (1) add a data-test attribute to the component, (2) find the component using that attribute, and then (3) check that only 1 component is found.
Useful helper functions
This function finds nodes in a wrapper with a given data-test attribute:
This function sets up and returns a ShallowWrapper component by encapsulating all configuration in a function:
Finding child nodes, managing state, and simulating events
Let's test that a button click increments a counter display. This will use:
stateandsetStatefor state managementfindfor finding child nodessimulatefor simulating eventstextto get inner text of node
Note: We use toContain because that allows you to change the text content inside counterDisplay without causing test failure.
propTypes testing
If your component has propTypes set up, you can run tests using check-prop-types to check that your propTypes are doing their job by only accepting the correct props.
Using checkPropTypes inside checkProps, a propsError message is returned if the provided props don't adhere to propTypes. We then check to see if there is in fact an error message using expect.
Contexts, describe, and forEach
We can wrap a set of test functions inside a describe function, creating a context in which all those tests fall under.
For example, a counter may have a set of tests for testing the increment portion of the counter:
Notice how we write const wrapper = setup() before each test? For code that you're repeating, you can move this to a beforeEach. beforeEach will run the code before each test.
Last updated