sbatson5 / firestore-jest-mock

Jest Helper library for mocking Cloud Firestore
https://www.npmjs.com/package/firestore-jest-mock
178 stars 59 forks source link

Cannot fetch values from mocked db #43

Closed FrozenKiwi closed 4 years ago

FrozenKiwi commented 4 years ago

Description

Queries return 0 docs

Steps to reproduce

The following minimal example is built from help docs & tests in this repo:

import { mockFirebase } from "firestore-jest-mock";

mockFirebase({
  database: {
    users: [
      { id: "abc123", name: "Homer Simpson" },
      { id: "abc456", name: "Lisa Simpson" },
    ],
    posts: [{ id: "123abc", title: "Really cool title" }],
  },
});
const firebase = require('firebase');
firebase.initializeApp({
  apiKey: '### FIREBASE API KEY ###',
  authDomain: '### FIREBASE AUTH DOMAIN ###',
  projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
const db = firebase.firestore();

test('testing stuff', () => {

  db.collection('users')
    .get()
    .then((userDocs: any) => {
      // write assertions here
      expect(userDocs.docs.length).toBe(2);
    });
})

Expected result

test should pass

Actual result

Fails with recieved: 0, expected 2.

Environment

FrozenKiwi commented 4 years ago

I tried copying in the actual test from firestore-jest-mock and this had the same failures.

My setup may be a bit unusual because my monorepo connects to firestore from GoogleApps, website, & node (so there are a few different firestore apps, and a project disambiguates them to allow library code to be agnostic of the environment). If that is somehow relevant?

FrozenKiwi commented 4 years ago

For my case, I simply skipped mocking the firestore module (as I don't/cant directly use it anyway) and just instantiated FakeFirestore directly.

import { SetFirestore } from './firestore';
import { Timestamp } from './timestamp';
const mocks = require('firestore-jest-mock');

export async function init(database: object) {

  // Import the mocked db, and assign.
  Timestamp.init(mocks.FakeFirestore.Timestamp);
  SetFirestore(new mocks.FakeFirestore(database));
}

Ps. This project is a great find! Thanks so much!