2

Code.js

saveToFirebase = () => {
    let statusMsg = ""

    firebase
      .firestore()
      .collection("messages")
      .doc(this.state.field.email)
      .set(this.state.field)
      .then((statusMsg = "Your Message have been submitted successfully."))

    this.clearFields(statusMsg)
  }

Code.test.js

it("should call mock firebase module", () => {
            const docData = {
              field: {
                name: "Rob Bob",
                email: "[email protected]",
                phone: "9999999999",
                subject: "Test subject",
                message: "Test message",
              },
            }

            const docResult = {
              data: () => docData,
            }

            const get = jest.fn(() => Promise.resolve(docResult))
            const set = jest.fn()

            const doc = jest.fn(() => {
              return {
                set,
                get,
              }
            })
            const colllection = jest.fn((messages) => {
              return { doc }
            })
            const firestore = () => {
              return colllection
            }

            firebase.firestore = firestore

            const mockData = { fake: "data" }
            jest.clearAllMocks()
            wrapper.instance().saveToFirebase()
          })

While running the Code.test.js, it throws an error that firebase.firestore().collection() is not a function. Please suggest proper mocking of the firebase module for the above code and to add a case to check if firebase has successfully returned then, clearFields() is invoked.

2 Answers 2

5

You can use jest.spyOn(object, methodName) to mock firebase.firestore() function.

E.g. index.jsx:

import React, { Component } from 'react';
import firebase from 'firebase';

export default class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      field: { email: '[email protected]' },
    };
  }
  clearFields(statusMsg) {
    console.log(statusMsg);
  }
  saveToFirebase = () => {
    let statusMsg = '';

    return firebase
      .firestore()
      .collection('messages')
      .doc(this.state.field.email)
      .set(this.state.field)
      .then(() => {
        statusMsg = 'Your Message have been submitted successfully.';
        this.clearFields(statusMsg);
      });
  };
  render() {
    return <div>my component</div>;
  }
}

index.test.jsx:

import MyComponent from '.';
import { shallow } from 'enzyme';
import React from 'react';
import firebase from 'firebase';

describe('61358076', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should pass', async () => {
    const firestoreMock = {
      collection: jest.fn().mockReturnThis(),
      doc: jest.fn().mockReturnThis(),
      set: jest.fn().mockResolvedValueOnce(),
    };
    const clearFieldsSpy = jest.spyOn(MyComponent.prototype, 'clearFields');
    jest.spyOn(firebase, 'firestore').mockImplementationOnce(() => firestoreMock);
    const wrapper = shallow(<MyComponent></MyComponent>);
    await wrapper.instance().saveToFirebase();
    expect(firestoreMock.collection).toBeCalledWith('messages');
    expect(firestoreMock.doc).toBeCalledWith('[email protected]');
    expect(firestoreMock.set).toBeCalledWith({ email: '[email protected]' });
    expect(clearFieldsSpy).toBeCalledWith('Your Message have been submitted successfully.');
  });
});

unit test results with 100% coverage:

 PASS  stackoverflow/61358076/index.test.jsx (17.824s)
  61358076
    ✓ should pass (39ms)

  console.log stackoverflow/61358076/index.jsx:1611
    Your Message have been submitted successfully.

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.jsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        19.945s

source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61358076

1
  • 2
    Interesting test email Mar 11, 2022 at 18:16
0

Hi recently I needed to mock jest module and this is my implementation, note: I used eventEmitter3 to handle onAuthStateChange

import EventEmitter from 'eventemitter3';

const authEmitter = new EventEmitter();
let isSignIn = true;
const user = {
    displayName: 'test name',
    email: '[email protected]',
    emailVerified: true,
    uid: 'id123',
    providerData: [
        {
            email: '[email protected]',
            displayName: 'redirectResultTestDisplayName',
            providerId: 'google',
        },
    ],
};

const mockFirebase: any = {
    initializeApp: jest.fn().mockReturnValue({
        auth: jest.fn().mockReturnValue({
            currentUser: isSignIn
                ? {
                        displayName: 'redirectResultTestDisplayName',
                        email: '[email protected]',
                        emailVerified: true,
                        uid: 'id123',
                        providerData: [
                            {
                                email: '[email protected]',
                                displayName: 'redirectResultTestDisplayName',
                                providerId: 'google',
                            },
                        ],
                        sendEmailVerification: jest.fn(),
                  }
                : null,
            signInWithRedirect: jest.fn(),
            getRedirectResult: jest.fn().mockReturnValue({
                credential: {
                    providerId: 'Google',
                },
                user: {
                    getIdToken: jest.fn().mockResolvedValue('abc1234'),
                },
                additionalUserInfo: {
                    profile: {
                        email: '__tests__@__tests__.com',
                        name: 'John Doe',
                    },
                },
            }),
            onAuthStateChanged: jest.fn(fn => {
                // sign user on start
                fn(user);
                // sign-out user on start
                authEmitter.on('sign-out', fn, undefined);
                authEmitter.on('sign-in', fn, user);
            }),
            signOut: jest.fn(() => {
                isSignIn = false;
                authEmitter.emit('sign-out');
            }),
            signInWithEmailAndPassword: jest.fn(() => {
                isSignIn = true;
                authEmitter.emit('sign-in', user);
                return Promise.resolve(true);
            }),
            sendPasswordResetEmail: jest.fn(() => Promise.resolve(true)),
            sendEmailVerification: jest.fn(() => Promise.resolve(true)),
            signInWithPopup: jest.fn(() => {
                isSignIn = true;
                authEmitter.emit('sign-in', user);
                return Promise.resolve(true);
            }),
        }),
        firestore: jest.fn().mockReturnValue({
            collection: jest.fn().mockReturnValue({
                doc: jest.fn().mockReturnValue({
                    add: jest.fn().mockResolvedValue({
                        id: 'abc123',
                    }),
                    set: jest.fn().mockResolvedValue({
                        uid: 'abc123',
                    }),
                }),
            }),
        }),
    }),
    auth: {
        GoogleAuthProvider: class {
            addScope = jest.fn();
        },
        GithubAuthProvider: class {
            addScope = jest.fn();
        },
        FacebookAuthProvider: class {
            addScope = jest.fn();
        },
    },
};

jest.mock('firebase/app', () => mockFirebase);
 
1
  • Its importent to add import '__mocks__/firebase'; to your setupTest.ts file Jul 25, 2020 at 18:37

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.