Home > Mobile >  Why jest mock is not mocking up a Firestore collection onSnapshot function?
Why jest mock is not mocking up a Firestore collection onSnapshot function?

Time:02-15

As said in title, I have no clue why a function Database.collection(...).onSnapshot method is not picked up as a function.

A message error I get is: TypeError: Database.collection(...).onSnapshot is not a function

I'm trying to make it work like so:

  test.only('should react when a new record is created', async () => {
    jest.mock('@google-cloud/firestore', () => jest.fn(() => ({
      collection: jest.fn()
        .mockImplementationOnce(function () { return this })
        .mockImplementationOnce(function () { return this })
        .mockImplementationOnce(function () { return this })
        .mockImplementationOnce(function () { return this })
        .mockImplementationOnce(function () { return this })
        .mockImplementationOnce(function () { return this })
        .mockResolvedValueOnce(() => {
          return {
            onSnapshot: () => {} // HOW TO MAKE IT WORK AS A FUNCTION?
          }
        }),
      get: jest.fn().mockResolvedValue({ docs: [] }),
      doc: jest.fn().mockReturnThis(),
      set: jest.fn().mockReturnThis(),
      limit: jest.fn().mockReturnThis(),
      select: jest.fn().mockReturnThis()
    })))

    const StatisticsService = require('./index')

    await StatisticsService()
  })
Code logic:
const Firestore = require('@google-cloud/firestore')
const Database = new Firestore()

const collections = ['products', 'users', 'orders']

collections.forEach(collection => {
  Database.collection(collection).onSnapshot(snapshot => {
    console.log('           
  • Related