The Spaghetti Refactory Established 2015

Mocking with Jest and React Native

I’ve been building a React Native app and learning testing using Jest. It has been an interesting journey, and I’m not going to go in-depth on much of my approaches to this test suite, other than to share a few links to articles I found helpful.

Anyway, the meat and potatoes of this post is how to mock with Jest, specifically how I figured out how to mock a popular library called 'react-native-router-flux' in my unit tests.

I was testing an action following the code samples in this post, and one of my actions routed to a new scene:

// Actions.js
import { Actions } from 'react-native-router-flux'
// ...some codes...

I don’t feel the need to test that transition while unit testing that specific action, but the test tries to run that code and horks badly. So I want to stub or mock the Actions somehow so I can test everything else in that action. After lots of trial and error and Googling, a colleague shared with me a StackOverflow post that had the key:

// testHelper.js
export default jest.mock(
  'react-native-router-flux', () => ({
    Actions: {
      replace: jest.fn(),
      // whatever other Actions you use in your code
// Actions.test.js
import 'testHelper.js'
import { Actions } from 'react-native-router-flux'

Now I can test only that the expected actions are fired:

  const expectedActions = [
    { type: 'LOGIN/SET_LOGIN_ERROR', message: '' },
    { type: 'LOGIN/STORE_SOMETHING', something: 'stuff' },

    .dispatch(LoginActions.sendLogin(username, password))
    .then(() => {