React Native + Jest + react-native-firebase = mock ❤
Have you ever been in troubles because your React Native app’s tests were all failing and it was all caused by react-native-firebase?
Recently I’ve integrated react-native-firebase on a React Native app and had a rough time...
Everything was wonderful, unicorns were flying through push notifications and my day was almost done until I’ve done npm run test!
RNFirebase core module was not found natively on iOS, ensure you have correctly included the RNFirebase pod in your projects `Podfile` and have run `pod install`.
After researching for similar problems, I found out that most of the people had this problem during the app’s build process which was not my case.
I tried reinstalling Pods, upgraded cocoapods and nothing worked… But since my problems were only related to tests, I just mocked react-native-firebase and everything becomes nice!
This was the solution (mockFirebase.js):
jest.mock('react-native-firebase', () => { return { messaging: jest.fn(() => { return { hasPermission: jest.fn(() => Promise.resolve(true)), subscribeToTopic: jest.fn(), unsubscribeFromTopic: jest.fn(), requestPermission: jest.fn(() => Promise.resolve(true)), getToken: jest.fn(() => Promise.resolve('myMockToken')) }; }), notifications: jest.fn(() => { return { onNotification: jest.fn(), onNotificationDisplayed: jest.fn() }; }) };});
I just mocked messaging and notifications because were the only ones I required from react-native-firebase.
Finally, I had to set mockFirebase.js as setup test file on package.json:
“jest”: { “setupTestFrameworkScriptFile”: “./__mocks__/mockFirebase”,
“automock”: false}