Ludwig Vantours
Ludwig Vantours

Reputation: 11

Test firebase cloud messaging with Jest

I am trying to test firebase cloud messaging with jest but I have an error with my mock function...

How can I test all function invocations?

expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called.

import { Sentry, SentrySeverity } from 'react-native-sentry';
import RNFirebase from 'react-native-firebase';
import Veery from 'react-native-veery';

export default function firebaseCloudMessaging() {
  try {
    const firebase = RNFirebase.app().messaging();

    firebase.getToken().then(Veery.setVeeryToken);

    firebase.getInitialNotification();

    firebase.onMessage(Veery.VeeryNotificationHandler);

    firebase.onTokenRefresh(Veery.setVeeryToken);
  } catch (error) {
    Sentry.captureException(error, { level: SentrySeverity.Error });
    console.warn('Error with firebaseCloudMessaging ', error);
  }
}

my test : https://gist.github.com/ludwigCDSBDX/82749eb20eac44fffac8d5318864eb6f

Thank you!

Upvotes: 0

Views: 1020

Answers (1)

Ludwig Vantours
Ludwig Vantours

Reputation: 11

my mistake: the previous mock creates several instances of mock so when I was trying to check if my mock had been called, I was comparing the same function, but not the same function instance !

jest.mock('react-native-firebase', () => {
  const app = { messaging: () => messaging };

  const messaging = {
    getToken: jest.fn(() => Promise.resolve('myTokenMock')),
    getInitialNotification: jest.fn(),
    onMessage: jest.fn(),
    onTokenRefresh: jest.fn(() => Promise.resolve('myMockTokenRefresh')),
  };

return { app: () => app };
});

Upvotes: 1

Related Questions