TypeError: firebase_admin_1.default.messaging is not a function

Viewed 235

I am trying to write unit tests using jest and trying to mock firebase-admin. Here is my application code:

import logger from './logger';
import admin from 'firebase-admin';

class NotificationService {
  constructor() {
    admin.initializeApp({
      credential: admin.credential.cert({
        projectId: 'FCM_PROJECT_ID',
        privateKey: 'FCM_PRIVATE_KEY'
        clientEmail: 'FCM_CLIENT_EMAIL'
      }),
    });
  }

  public async send(message: TokenMessage): Promise<ApiResponse<string>> {
    try {
      await admin.messaging().send(message)
    } catch (e) {
      logger.error(e);
    }
  }
}

I am trying to mock the code like below:

jest.mock('firebase-admin');

But it is erroring out with:

firebase_admin_1.default.messaging is not a function

What is the solution?

1 Answers

Issue: not mocking the member variables and methods(messaging, send) of firebase-admin.

Fix:

jest.mock('firebase-admin', () => ({
  messaging: jest.fn().mockImplementation(() => {
    return {
      send: jest
        .fn()
        .mockReturnValue('message_id'),
    };
  }),
}));

Note: You would probably need to mock credential and initializeApp as well:

jest.mock('firebase-admin', () => ({
      credential: {
        cert: jest.fn(),
      },
      initializeApp: jest.fn(),
      messaging: jest.fn().mockImplementation(() => {
        return {
          send: jest
            .fn()
            .mockReturnValue('message_id'),
        };
      }),
    }));
Related