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')
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' },
]
store
.dispatch(LoginActions.sendLogin(username, password))
.then(() => {
expect(store.getActions()).toEqual(expectedActions)
done()
})
Versions:
"jest": "22.4.4"
"jest-expo": "27.0.1"
"react-native": "0.55.2"
"react-native-router-flux": "4.0.0-beta.32"
Top comments (1)
Thank you very much, i am also learning about jest, and was facing a lot of issues related to router-flux, you fixed it!