Learning to test React Native with Jest — part 1

It’s a snap!(shot)

Jason Gaare
May 25, 2017 · 5 min read
Image for post
Image for post

Adding Jest to our project

1. Installing packages

2. Just a few more lines before we can get testing…

// Add this to your package.json
"scripts": {
"test": "jest"
},
"jest": {
"preset": "react-native"
}
// Add this to your .babelrc
{
"presets": ["react-native"]
}

3. Creating our first test

Doing more with Snapshots (enter: Enzyme)

"jest": {
"preset": "react-native",
"snapshotSerializers": [
"./node_modules/jest-serializer-enzyme"
]
},

Test rendering connected components

export default connect(mapStateToProps)(CameraSettings);

An okay way… (avoid the state)

// components/menu/CameraSettings.js
export class CameraSettings extends Component { ... }
// __tests__/components/menu/CameraSettings.test.js
import { CameraSettings } from 'components/menu/CameraSettings';

The better way (mock the state!)

Having a mocked state allows us to test the functionality of mapStateToProps rather than duplicating its logic in our test file.

We’ve only dipped our toes in the water so far

More in this series:

React Native Training

Stories and tutorials for developers interested in React…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store