3

I'm trying to use jest.useFakeTimers() to make my firebase + jest tests stable when working with dates and timeouts. However, if I try to read anything from the emulated database the test times out and throws Exceeded timeout of 5000 ms for a test. Using jest.setTimeout(30000) doesn't help.

Github repro: https://github.com/vojdan/jest-fake-timers-firebase

Here's the test:

import * as admin from "firebase-admin";

// jest.setTimeout(30000);

describe("emulated firebase test", () => {
  beforeAll(() => {
    jest.useFakeTimers();
    jest.setSystemTime(1349852318000);

    admin.initializeApp({
      projectId: "test-project",
      databaseURL: "http://localhost:9000?ns=test-project",
    });
  });
  afterAll(() => {
    jest.useRealTimers();
  });

  it("only passes with fake timers", () => {
    expect.assertions(1);

    expect(new Date().valueOf()).toBe(1349852318000);
  });
  it("hangs when fake timers are used", async () => {
    expect.assertions(1);

    try {
      const firestore = admin.firestore().doc("anything/really");
      const realtime = admin.database().ref("anyhting/really");
      console.log("this runs:", new Date().valueOf());
      // ----- EVERYTHING RUNS UP TO HERE -----

      // ----- any of the following commands will block when used with jest.useFakeTimers(); -----
      // await firestore.get();
      const ref = await realtime.once("value");
      const value = ref.val();
      console.log("this doesn't run:", value);

      expect(1).toBe(1);
    } catch (error) {
      console.log("THERE WAS AN ERROR:", error);
    }
  });
});


samurai jack
  • 401
  • 1
  • 7
  • 10

1 Answers1

0

Since useFakeTimers isn't working for me, I'm using this as a workaround:

jest.mock('date-fns', () => {
    // Require the original module to not be mocked...
    const originalModule = jest.requireActual('date-fns');

    return {
        ...originalModule,
        getTime: jest.fn(() => mockedTimestamp),
        getUnixTime: jest.fn(() => mockedTimestampUnix),
        format: jest.fn(input => 'mockedTimeString'),
    };
});
samurai jack
  • 401
  • 1
  • 7
  • 10