dmurvihill / firebase-mock

Firebase mock library for writing unit tests
55 stars 21 forks source link

Clear, reset or erase Firestore database in each test #73

Open dev-andremonteiro opened 3 years ago

dev-andremonteiro commented 3 years ago

I have posted to this issue in the old repository, but it seems like we moved to this repository so I might as well post here, sorry about that I didn't know issues should be moved to this one.

I have been trying to reset my firestore database so my tests don't have remaining data from past tests, I have found some resources in the issue linked above but I can't seem to get the database reset even after making the reassignment of the firestore variable.

jest.mock('../init', () => {
  const firebasemock = require('firebase-mock');

  let mockauth = new firebasemock.MockAuthentication();
  let mockstorage = new firebasemock.MockStorage();
  let mockfirestore = new firebasemock.MockFirestore();
  mockfirestore.autoFlush();

  return {
    reset: function() {
      const mockAut = new firebasemock.MockAuthentication();
      const mockStor = new firebasemock.MockStorage();
      const mockFire = new firebasemock.MockFirestore();
      mockFire.autoFlush();

      this.auth = mockAut;
      this.storage = mockStor;
      this.firestore = mockFire;
    },
    firestore: mockfirestore,
    auth: mockauth,
    storage: mockstorage,
    functions: jest.fn()
  };
});

Maybe some of you know how to do this in version 2.3.2, do we have a function that makes this in the library ?

alexlouden commented 3 years ago

I'm not sure it's the correct way to do it, but this is what I use:

test utils:

const firestoreDeleteChildren = ref => {
  // Firestore recursive delete
  Object.values(ref.children).forEach(child => {
    firestoreDeleteChildren(child)
    if (child.delete) {
      child.delete()
    }
  })

exports.clearFirestore = () => {
  const { firestore } = require('./pathToYourFirestoreInit')
  // safe!
  if (firestore.constructor.name === 'MockFirestore') {
    console.log('Clearing MockFirestore')
    firestoreDeleteChildren(firestore)
  }
}

in tests:

const { clearFirestore } = './testUtils'

beforeEach(() => {
  clearFirestore()
})