Test Firebase RealtimeDatabase using Jest











up vote
2
down vote

favorite
1












My purpose is simply to test one function. I cannot figure out how to mock firebase properly. I try to keep the example with axios mocking from Jest docs. I have the following code:



MusicService.js



import { initializeApp } from "firebase/app";
import "firebase/database";

const firebase = initializeApp({
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
projectId: "<PROJECT_ID>",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
});

export class MusicService {
static getAlbums() {
return firebase.database().ref("albums").once("value")
.then(snapshot => Object.values(snapshot.val()));
}
}


MusicService.test.js



import firebase from 'firebase/app';
import 'firebase/database';
import { MusicService } from './MusicService';

jest.mock('firebase/app');
jest.mock('firebase/database');

test("test", () => {
firebase.initializeApp.mockImplementation(() => {
database: jest.fn(() => {
return {
ref: jest.fn()
}
})
});

MusicService.getAlbums();
});


The problem is that I get the following error:
enter image description here



I tried to mock firebase.database.



test("test", () => {
firebase.mockImplementation(() => {
return {
database: {

}
}
});
MusicService.getAlbums();
});


But in this case I get the error that says:




TypeError: _app.default.mockImplementation is not a function.




I don't expect the working example will be given, but rather could you tell please, what exactly should I mock? The whole firebase library or maybe the part where my function starts - return firebase.database().










share|improve this question




























    up vote
    2
    down vote

    favorite
    1












    My purpose is simply to test one function. I cannot figure out how to mock firebase properly. I try to keep the example with axios mocking from Jest docs. I have the following code:



    MusicService.js



    import { initializeApp } from "firebase/app";
    import "firebase/database";

    const firebase = initializeApp({
    apiKey: "<API_KEY>",
    authDomain: "<PROJECT_ID>.firebaseapp.com",
    databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
    projectId: "<PROJECT_ID>",
    storageBucket: "<BUCKET>.appspot.com",
    messagingSenderId: "<SENDER_ID>",
    });

    export class MusicService {
    static getAlbums() {
    return firebase.database().ref("albums").once("value")
    .then(snapshot => Object.values(snapshot.val()));
    }
    }


    MusicService.test.js



    import firebase from 'firebase/app';
    import 'firebase/database';
    import { MusicService } from './MusicService';

    jest.mock('firebase/app');
    jest.mock('firebase/database');

    test("test", () => {
    firebase.initializeApp.mockImplementation(() => {
    database: jest.fn(() => {
    return {
    ref: jest.fn()
    }
    })
    });

    MusicService.getAlbums();
    });


    The problem is that I get the following error:
    enter image description here



    I tried to mock firebase.database.



    test("test", () => {
    firebase.mockImplementation(() => {
    return {
    database: {

    }
    }
    });
    MusicService.getAlbums();
    });


    But in this case I get the error that says:




    TypeError: _app.default.mockImplementation is not a function.




    I don't expect the working example will be given, but rather could you tell please, what exactly should I mock? The whole firebase library or maybe the part where my function starts - return firebase.database().










    share|improve this question


























      up vote
      2
      down vote

      favorite
      1









      up vote
      2
      down vote

      favorite
      1






      1





      My purpose is simply to test one function. I cannot figure out how to mock firebase properly. I try to keep the example with axios mocking from Jest docs. I have the following code:



      MusicService.js



      import { initializeApp } from "firebase/app";
      import "firebase/database";

      const firebase = initializeApp({
      apiKey: "<API_KEY>",
      authDomain: "<PROJECT_ID>.firebaseapp.com",
      databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
      projectId: "<PROJECT_ID>",
      storageBucket: "<BUCKET>.appspot.com",
      messagingSenderId: "<SENDER_ID>",
      });

      export class MusicService {
      static getAlbums() {
      return firebase.database().ref("albums").once("value")
      .then(snapshot => Object.values(snapshot.val()));
      }
      }


      MusicService.test.js



      import firebase from 'firebase/app';
      import 'firebase/database';
      import { MusicService } from './MusicService';

      jest.mock('firebase/app');
      jest.mock('firebase/database');

      test("test", () => {
      firebase.initializeApp.mockImplementation(() => {
      database: jest.fn(() => {
      return {
      ref: jest.fn()
      }
      })
      });

      MusicService.getAlbums();
      });


      The problem is that I get the following error:
      enter image description here



      I tried to mock firebase.database.



      test("test", () => {
      firebase.mockImplementation(() => {
      return {
      database: {

      }
      }
      });
      MusicService.getAlbums();
      });


      But in this case I get the error that says:




      TypeError: _app.default.mockImplementation is not a function.




      I don't expect the working example will be given, but rather could you tell please, what exactly should I mock? The whole firebase library or maybe the part where my function starts - return firebase.database().










      share|improve this question















      My purpose is simply to test one function. I cannot figure out how to mock firebase properly. I try to keep the example with axios mocking from Jest docs. I have the following code:



      MusicService.js



      import { initializeApp } from "firebase/app";
      import "firebase/database";

      const firebase = initializeApp({
      apiKey: "<API_KEY>",
      authDomain: "<PROJECT_ID>.firebaseapp.com",
      databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
      projectId: "<PROJECT_ID>",
      storageBucket: "<BUCKET>.appspot.com",
      messagingSenderId: "<SENDER_ID>",
      });

      export class MusicService {
      static getAlbums() {
      return firebase.database().ref("albums").once("value")
      .then(snapshot => Object.values(snapshot.val()));
      }
      }


      MusicService.test.js



      import firebase from 'firebase/app';
      import 'firebase/database';
      import { MusicService } from './MusicService';

      jest.mock('firebase/app');
      jest.mock('firebase/database');

      test("test", () => {
      firebase.initializeApp.mockImplementation(() => {
      database: jest.fn(() => {
      return {
      ref: jest.fn()
      }
      })
      });

      MusicService.getAlbums();
      });


      The problem is that I get the following error:
      enter image description here



      I tried to mock firebase.database.



      test("test", () => {
      firebase.mockImplementation(() => {
      return {
      database: {

      }
      }
      });
      MusicService.getAlbums();
      });


      But in this case I get the error that says:




      TypeError: _app.default.mockImplementation is not a function.




      I don't expect the working example will be given, but rather could you tell please, what exactly should I mock? The whole firebase library or maybe the part where my function starts - return firebase.database().







      javascript firebase unit-testing firebase-realtime-database jestjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 10 at 23:15









      LazerBass

      1,23431021




      1,23431021










      asked Nov 10 at 12:39









      Lucknee

      327




      327
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          I have figured out. I should mock only those modules, a function I am going to test, depends on. For example, I want to test getAlbums function. It uses initializeApp function which is imported from firebase/app module in MusicService.js. So when initializeApp function is being called it should return an object containing database function which in turn returns an object with ref and once functions. Code:



          MusicService.test.js.



          import { MusicService } from "./FirebaseService";

          jest.mock("firebase/app", () => {
          const data = { name: "unnamed" };
          const snapshot = { val: () => data };
          return {
          initializeApp: jest.fn().mockReturnValue({
          database: jest.fn().mockReturnValue({
          ref: jest.fn().mockReturnThis(),
          once: jest.fn(() => Promise.resolve(snapshot))
          })
          })
          };
          });

          test("getAlbums function returns an array", async () => {
          const data = await MusicService.getAlbums();
          expect(data.constructor).toEqual(Array);
          });





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53239045%2ftest-firebase-realtimedatabase-using-jest%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            I have figured out. I should mock only those modules, a function I am going to test, depends on. For example, I want to test getAlbums function. It uses initializeApp function which is imported from firebase/app module in MusicService.js. So when initializeApp function is being called it should return an object containing database function which in turn returns an object with ref and once functions. Code:



            MusicService.test.js.



            import { MusicService } from "./FirebaseService";

            jest.mock("firebase/app", () => {
            const data = { name: "unnamed" };
            const snapshot = { val: () => data };
            return {
            initializeApp: jest.fn().mockReturnValue({
            database: jest.fn().mockReturnValue({
            ref: jest.fn().mockReturnThis(),
            once: jest.fn(() => Promise.resolve(snapshot))
            })
            })
            };
            });

            test("getAlbums function returns an array", async () => {
            const data = await MusicService.getAlbums();
            expect(data.constructor).toEqual(Array);
            });





            share|improve this answer



























              up vote
              0
              down vote













              I have figured out. I should mock only those modules, a function I am going to test, depends on. For example, I want to test getAlbums function. It uses initializeApp function which is imported from firebase/app module in MusicService.js. So when initializeApp function is being called it should return an object containing database function which in turn returns an object with ref and once functions. Code:



              MusicService.test.js.



              import { MusicService } from "./FirebaseService";

              jest.mock("firebase/app", () => {
              const data = { name: "unnamed" };
              const snapshot = { val: () => data };
              return {
              initializeApp: jest.fn().mockReturnValue({
              database: jest.fn().mockReturnValue({
              ref: jest.fn().mockReturnThis(),
              once: jest.fn(() => Promise.resolve(snapshot))
              })
              })
              };
              });

              test("getAlbums function returns an array", async () => {
              const data = await MusicService.getAlbums();
              expect(data.constructor).toEqual(Array);
              });





              share|improve this answer

























                up vote
                0
                down vote










                up vote
                0
                down vote









                I have figured out. I should mock only those modules, a function I am going to test, depends on. For example, I want to test getAlbums function. It uses initializeApp function which is imported from firebase/app module in MusicService.js. So when initializeApp function is being called it should return an object containing database function which in turn returns an object with ref and once functions. Code:



                MusicService.test.js.



                import { MusicService } from "./FirebaseService";

                jest.mock("firebase/app", () => {
                const data = { name: "unnamed" };
                const snapshot = { val: () => data };
                return {
                initializeApp: jest.fn().mockReturnValue({
                database: jest.fn().mockReturnValue({
                ref: jest.fn().mockReturnThis(),
                once: jest.fn(() => Promise.resolve(snapshot))
                })
                })
                };
                });

                test("getAlbums function returns an array", async () => {
                const data = await MusicService.getAlbums();
                expect(data.constructor).toEqual(Array);
                });





                share|improve this answer














                I have figured out. I should mock only those modules, a function I am going to test, depends on. For example, I want to test getAlbums function. It uses initializeApp function which is imported from firebase/app module in MusicService.js. So when initializeApp function is being called it should return an object containing database function which in turn returns an object with ref and once functions. Code:



                MusicService.test.js.



                import { MusicService } from "./FirebaseService";

                jest.mock("firebase/app", () => {
                const data = { name: "unnamed" };
                const snapshot = { val: () => data };
                return {
                initializeApp: jest.fn().mockReturnValue({
                database: jest.fn().mockReturnValue({
                ref: jest.fn().mockReturnThis(),
                once: jest.fn(() => Promise.resolve(snapshot))
                })
                })
                };
                });

                test("getAlbums function returns an array", async () => {
                const data = await MusicService.getAlbums();
                expect(data.constructor).toEqual(Array);
                });






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 19 at 9:53

























                answered Nov 17 at 19:53









                Lucknee

                327




                327






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53239045%2ftest-firebase-realtimedatabase-using-jest%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    鏡平學校

                    ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

                    Why https connections are so slow when debugging (stepping over) in Java?