How do you mock Firebase Firestore methods using Jest?

前端 未结 7 1777
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 17:12

I have a series of functions, each performing various firestore interactions. How do I use Jest to mock these firestore calls? I would like to avoid using a library.

7条回答
  •  清酒与你
    2020-12-17 17:49

    Here is the solution I have found. There isn't much information online about this, so I hope it helps someone.

    EDIT: I believe you can do something similar using jests /__MOCKS__/ folders system, rather than overwriting the firestore object as I do in this example.

    The trick is to create a chained API of mock functions, and set this on the firebase object, instead of importing and mocking firestore. The example below allows me to test the above example function, and also doc().get() promises.

    const docData = { data: "MOCK_DATA" };
    const docResult = {
      // simulate firestore get doc.data() function
      data: () => docData
    };
    const get = jest.fn(() => Promise.resolve(docResult));
    const set = jest.fn();
    const doc = jest.fn(() => {
      return {
        set,
        get
      };
    });
    const firestore = () => {
      return { doc };
    };
    firestore.FieldValue = {
      serverTimestamp: () => {
        return "MOCK_TIME";
      }
    };
    
    export { firestore };
    

    I declare it in a file that runs before all my tests do (see docs), and import and use it in my test files like this:

    import firebase from "firebase/app";
    import { firestore } from "../setupTests";
    firebase.firestore = firestore;
    
    describe("setDocData", () => {
      const mockData = { fake: "data" };
      beforeEach(() => {
        jest.clearAllMocks();
        setDocData("fakeDocID", mockData);
      });
    
      it("writes the correct doc", () => {
        expect(firestore().doc).toHaveBeenCalledWith("docs/fakeDocID");
      });
    
      it("adds a timestamp, and writes it to the doc", () => {
        expect(firestore().doc().set).toHaveBeenCalledWith({
          created: "MOCK_TIME",
          fake: "data"
        });
      });
    });
    

提交回复
热议问题