Giter VIP home page Giter VIP logo

Comments (5)

sbatson5 avatar sbatson5 commented on July 1, 2024

Thanks for posting. Based off the path /node_modules/@firebase/firestore/src/util/error.ts:217:5 it looks like your test is hitting the real firestore, so it isn't using the mock. We also don't throw any errors like that, so my guess it comes from firebase directly.

How do you set up the mock in your test suite? Sometimes jest can be frustrating with the way it hoists functions calls, so the mock might be getting called after your app spins up.

from firestore-jest-mock.

AlphaNiner1415 avatar AlphaNiner1415 commented on July 1, 2024

So this is how my testing file is setup:

At the top of the file I have:

import { updateUser, currentUserListener, returnFirestore, createNewsArticle, getUserDocument } from './firebase';
import "firebase/auth";

const { mockFirebase } = require('firestore-jest-mock');
const { mockInitializeApp } = require('firestore-jest-mock/mocks/firebase');

mockFirebase({
        database: {
            users: [
                {
                    id: "a1",
                    displayName: "Homer Simpson",
                    phoneNumber: "1234815785",
                    email: "[email protected]",
                    dateOfBirth: new Date("10 February, 2000"),
                    photoURL: "http://google.co.th",
                },
                {
                    id: "a2",
                    displayName: "Bart Simpson",
                    phoneNumber: "3874384783",
                    email: "[email protected]",
                    dateOfBirth: new Date("10 February, 2000"),
                    photoURL: "http://google.co.th",
                },
            ],
            news: [
                {
                    id: "1",
                    authorName: "Homer Simpson",
                    datePublished: "2000/01/01",
                    dateUpdated: new Date(),
                    category: 'Sports',
                    hits: 2,
                    content: "jskl;dfja;lksdjfa",
                    previewContent: "kdf;alsdkjfa;lskdf",
                    title: "News Article 1",
                }
            ]
        }
    });

And this is the start of the test:

describe('The getUserDocument() function', () => {
    
    let firebase;
    let firestore;
    let autho;
    
    beforeEach(() => {
        jest.clearAllMocks();
        firebase = require("firebase"); // or import firebase from 'firebase';
        autho = firebase.auth();
        firestore = firebase.firestore();
        
    });

Now I'm starting to think it's all about variable naming, because now inside the files that stores the function (firebase.js) I have the variables initialized like this: ( the firebaseConfig is of course initialized with real app settings, I'm just replacing it with placeholders so as to not expose my app )

const firebaseConfig =  {
    apiKey: "MY APP'S KEY",
    authDomain: "PROJECTID.firebaseapp.com",
    projectId: "PROJECTID",
    storageBucket: "PROJECTID.appspot.com",
    messagingSenderId: "RANDOMNUMBER",
    appId: "APPID",
    measurementId: "MEASUREMENTID",
};
const fire = firebase.initializeApp(firebaseConfig);
export const auth = firebase.auth();
export const firestore = firebase.firestore();

And so inside the function inside firebase.js when I call the doc I call it like so:
firestore.doc(users/${uid}).get();
I'm thinking if I change it to:
firebase.firestore().doc(users/${uid}).get();

It might allow the mockFirebase to override it. However, I would prefer a way where I didn't have to do that for each and every function.

from firestore-jest-mock.

AlphaNiner1415 avatar AlphaNiner1415 commented on July 1, 2024

Ok so update, changing firestore.doc(users${uid}).get(); to firebase.firestore().doc(users/${uid}).get(); doesn't work

However, if I copy the whole function from the file with my firebase functions and paste it into my test file below the describe then that successfully tests it:

describe('The getUserDocument() function', () => {
    const getUserDocument = async (uid) => {
    if (!uid) return null;
    try {
        const userDocument = await firestore.doc(`users/${uid}`).get();
        return {
            uid,
            ...userDocument.data(),
        };
    } catch (error) {
        console.error("Error fetching user", error);
    }
   };
    let firebase;
    let firestore;
    let autho;
    
    beforeEach(() => {
        jest.clearAllMocks();
        firebase = require("firebase"); // or import firebase from 'firebase';
        autho = firebase.auth();
        firestore = firebase.firestore();
        
    });

This works

from firestore-jest-mock.

sbatson5 avatar sbatson5 commented on July 1, 2024

If you move the mockFirebase call into the describe block, does that fix it? Having it live outside of the test might be causing a scoping issue. Take a look at some of our tests as an example:
https://github.com/Upstatement/firestore-jest-mock/blob/master/__tests__/query.test.js#L12

from firestore-jest-mock.

sbatson5 avatar sbatson5 commented on July 1, 2024

Closing due to inactivity. Feel free to re-open if you still have questions

from firestore-jest-mock.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.