Below mentioned mocked function when used in a file called useFirestore gives the following error: Cannot read property 'collection' of undefined.
firebase.js
import Firebase from 'firebase/app';
import 'firebase/storage';
import 'firebase/firestore';
import 'firebase/auth';
const config = {'// Firebase config'};
const firebase = !Firebase.apps.length ? Firebase.initializeApp(config) : Firebase.app;
export const { serverTimestamp } = Firebase.firestore.FieldValue;
export default firebase;
setupTests.js
import '@testing-library/jest-dom';
jest.mock('./firebase', () => ({
storage: jest.fn(),
firestore: jest.fn().mockReturnedValue({
collection: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
onSnapshot: jest.fn().mockReturnThis(),
}),
}));
Custom Hook
import firebase from '../firebase';
function useFirestore(collectionName) {
const [docs, setDocs] = React.useState(null);
const [loading, setLoading] = React.useState(true);
React.useEffect(() => {
const unsub = firebase
.firestore() // logs cannot read property collection of undefined
.collection(collectionName)
.orderBy('createdAt', 'desc')
.onSnapshot(
(snapshot) => {
setDocs(snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() })));
setLoading(false);
},
(err) => {
console.log(err);
}
);
return unsub;
}, [collectionName]);
return {
docs,
loading,
};
}
export default useFirestore;
jest.config.js
module.exports = {
collectCoverageFrom: [
'src/**/*.{js,jsx}',
'!<rootDir>/node_modules/',
'!<rootDir>/coverage/',
'!<rootDir>/build/',
],
moduleNameMapper: { '\\.(css|scss)$': '<rootDir>/src/utils/__mocks__/stylemock.js' },
setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
};
As mentioned the above configuration returns undefined. However, when I change the mock implemenation of firestore to the following, it works correctly.
jest.mock('./firebase', () => ({
storage: jest.fn(),
firestore: () => ({ // not using jest.fn() and mockReturnValue
collection: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
onSnapshot: jest.fn().mockReturnThis(),
}),
}));
Please guide if anything's wrong here. Thanks