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

Fix jest error on missing dependencies #28

Closed a-mroz closed 4 years ago

a-mroz commented 4 years ago

Description

In our project, we use only firebase-admin package and there is no firebase module imported.

When I attempt to mock firestore in such scenario, it fails (Cannot find module 'firebase' from 'node_modules/firestore-jest-mock/mocks/firebase.js'). That's because jest can not find firebase module in this line: jest.doMock('firebase', () => firebaseStub(overrides));

This change applies mocking only if a respective module can be found as a dependency. require.resolve() was the best way I found to check if a package can be found, but it throws an exception if a module was not found - therefore the empty catch.

In addition, I changed the usage of the mock functions to doMock - when plain mocking was replaced with the function call the && trick did not work anymore and babel-plugin-jest-hoist reported an error: The module factory of jest.mock() is not allowed to reference any out-of-scope variables.

Related issues

How to test

Try mocking in a project which has a dependency to firebase-admin but not to firebase - before and after the change.