sbatson5 / firestore-jest-mock

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

Firestore instance in snapshot.ref go undefined after make a document query request to the database #125

Open ndpdarshana opened 3 years ago

ndpdarshana commented 3 years ago

Description

The QueryDocumentSnapshot passed to onCreate() trigger failed to retrieve FakeFirestore instance within its ref value after query a document from the database.

Steps to reproduce

  1. Write a onCreate() functions trigger
    
    export const setupActionTrigger = () => {
     return functions.firestore.document('note/{id}').onCreate(async(snapshot) => {
       if(snapshot.exists){
         console.log(snapshot.ref);
         const userRef = await admin.firestore().doc(`users/123`}).get();
         console.log(snapshot.ref);
       }
     });
    }
  2. Make a test class

    describe('actionTrigger', () => {
     const test = firebaseFunctionsTest(); 
     let actionTriggerFunction: WrappedFunction;
    
     beforeAll(() => {
       fakeFirestore = new FakeFirestore({
         note: [{id: '123', note: 'test note', uid: 'xyz'}],
         users: [{id:'xyz', username: 'xyzlmn'}]
       });
       mockFirebase({database: fakeFirestore.database});
       admin.initializeApp();
    
       const {setupActionTrigger} = require('../src/test-trigger');
       actionTriggerFn = test.wrap(setupActionTrigger());
     }
    
     asterAll(() => {
       jest.clearAllMocks();
       jest.resetAllMocks();
       test.cleanup();
     });
    
    it('should pass', async () => {
      const doc = await fakeFirestore.doc('note/123').get();
      await actionTrigger(doc);
    })
    }
  3. Note that the first console.log in the trigger function for snapshot.ref print with FakeFirestore instance that provided by test suit.
  4. Note that the second console.log in the trigger function print without FakeFirestore instance, instead it says firestore:undefined

Expected result

Firesore instance with provided FakeFirestore instance would remain untouched with snapshot object after retrieving a document from the database query as shown in the trigger function

Actual result

The snapshot object reference FakeFirestore object went undefined after making the database query

Environment

ndpdarshana commented 3 years ago

I've just found out that this happens when calling the admin.firestor() call on the functions class. Somehow, admin.firestor() call resets the already obtained snapshot inside the trigger function.