DEV Community

Mark J. Lehman
Mark J. Lehman

Posted on • Originally published at supremebeing7.github.io on

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...
Actions.replace('afterLoginScene')

Enter fullscreen mode Exit fullscreen mode

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'

Enter fullscreen mode Exit fullscreen mode

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' },
  ]

  store
    .dispatch(LoginActions.sendLogin(username, password))
    .then(() => {
      expect(store.getActions()).toEqual(expectedActions)
      done()
    })

Enter fullscreen mode Exit fullscreen mode

Versions:

"jest": "22.4.4"
"jest-expo": "27.0.1"
"react-native": "0.55.2"
"react-native-router-flux": "4.0.0-beta.32"
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
ricardobrito1938 profile image
RicardoBrito1938

Thank you very much, i am also learning about jest, and was facing a lot of issues related to router-flux, you fixed it!