LoginSignup
0
1

More than 1 year has passed since last update.

JestのuseFakeTimersを使用するとFirestoreにアクセスできなくなる

Last updated at Posted at 2022-12-16

問題のコード

テストを書いていると、日時を固定したくなるケースがあると思う。
JestにはuseFakeTimers()という便利な関数があり、これを呼び出すことで、日時を固定したテストの実行が可能になる。
しかし、このuseFakeTimers()を呼び出すと、Firestoreにアクセスできず、テストがタイムアウトしてしまった。

index.test.ts
describe('test', () => {
  beforeAll(() => {
    // 日時を固定する
    jest.useFakeTimers();
    const fixedDate = new Date('2020-09-01T02:00:00+09:00');
    jest.setSystemTime(fixedDate);
  });

  afterAll(() => {
    // 日時の固定を解除する
    jest.useRealTimers();
  });

  it('Add document test', async () => {
    const ref = collection(firestore, 'tests');
    await addDoc(ref, { id: 'hoge' }); // アクセスできない

    const snapshot = await getDocs(ref);
    expect(snapshot.docs.length).toBe(1);
  });
});

対応策

  • テスト対象の関数から、Firestoreにアクセスする部分を切り出す
  • Jest以外の方法で日時を固定できないか試してみる

最後に

何か良い解決策が見つかったら、是非コメントで教えてください!
ちなみに、こちらにも同じ問題が上がっているが、特に解決していない。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1