简体   繁体   English

如何用玩笑重置我的 Cloud Functions 的 Firestore 单元测试

[英]How to reset firestore unit testing my Cloud Functions with jest

I followed the Cloud Functions recommendation and created my unit testing in online mode, everything makes sense to me, but I am getting inconsistency when I am debugging.我遵循 Cloud Functions 建议并在在线模式下创建了我的单元测试,一切对我来说都很有意义,但是在调试时我变得不一致。 I just trying to reset the firestore state by resetting and seeding the database.我只是试图通过重置和播种数据库来重置 Firestore state。

When I run my test suite separately, they work perfectly;当我单独运行我的测试套件时,它们运行良好; if I run all the test suites together appear all the errors, I am pretty sure that this is related to the beforeEach hooks but idk how to fix them.如果我一起运行所有测试套件出现所有错误,我很确定这与 beforeEach 挂钩有关,但我不知道如何修复它们。

I have 3 test suites, I will share with you 1 of them and the function responsible of the reset of the firestore.我有 3 个测试套件,我将与您分享其中 1 个以及负责重置 Firestore 的 function。

// eslint-disable-next-line spaced-comment
    /// <reference types="jest" />

    import { cleanup, getDb, initializeFirebase, makeChange, resetDb, wrap } from './util';
    initializeFirebase();

    import { streamerIsOffline, streamerIsOnline } from './__fixtures__/onStreamerUpdateSnaps';
    import { getScheduler, SchedulerClientWrapper } from './../utils/SchedulerClientWrapper';
    import onStreamerUpdate from '../onStreamerUpdate';

    const db = getDb();

    jest.mock('./../utils/SchedulerClientWrapper');

    const mockedGetScheduler = jest.mocked(getScheduler, true);

    const wrapped = wrap(onStreamerUpdate);

    const schedulerClientWrapper = new SchedulerClientWrapper();
    const mockedPause: jest.Mock = jest.fn();
    const mockedResume: jest.Mock = jest.fn();
    const mockedJobIsEnabled: jest.Mock = jest.fn();


    schedulerClientWrapper.pause = mockedPause;
    schedulerClientWrapper.resume = mockedResume;
    schedulerClientWrapper.jobIsEnabled = mockedJobIsEnabled;

    describe('onStreamerUpdate', () => {
      beforeEach(
          async () => {
            await resetDb(); //I am resetting firestore here
            mockedGetScheduler.mockClear();
            jest.resetAllMocks();
          });

      it('should resume the scheduledJob when the first streamer becomes online',
          async () => {
            await updateStreamerStatus('64522496', true); //I am preparing the setup here

            const beforeSnap = streamerIsOffline;
            const afterSnap = streamerIsOnline;

            const change = makeChange(beforeSnap, afterSnap);

            mockedGetScheduler.mockReturnValue(schedulerClientWrapper);

            mockedJobIsEnabled.mockResolvedValue(false);

            await wrapped(change);

            expect(mockedJobIsEnabled).toBeCalled();
            expect(mockedResume).toBeCalled();
            expect(mockedPause).not.toBeCalled();
          });
          
      afterAll(() => {
        cleanup();
      });
      
    });

    const updateStreamerStatus = async (streamerId: string, isOnline: boolean) => {
      const stremersRef = db.collection('streamers');

      const query = stremersRef.where('broadcasterId', '==', streamerId);
      const querySnapshot = await query.get();
      console.log('streamers', (await stremersRef.get()).docs.map((doc) => doc.data())); //I am debugging here
      const streamerDocId = querySnapshot.docs[0].id;
      await stremersRef.doc(streamerDocId).update({ isOnline });
    };

And you can find the functions that wipe and seed firestore below:您可以在下面找到擦除和播种 Firestore 的功能:

import firebaseFunctionsTest from 'firebase-functions-test';
import { getApp, getApps, initializeApp, cert } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore';

const projectId = 'latamqchallengetest';

export const { wrap, cleanup, firestore: firestoreTestData, makeChange } = firebaseFunctionsTest({
  databaseURL: `https://${projectId}.firebaseio.com`,
  storageBucket: `${projectId}.appspot.com`,
  projectId: projectId,
}, './../google-credentials/latamqchallengetest-firebase-adminsdk.json');

export const initializeFirebase = () => {
  if (getApps().length <= 0) {
    initializeApp({
      credential: cert('./../google-credentials/latamqchallengetest-firebase-adminsdk.json'),
    });
  }
  return getApp();
};

export const getDb = () => {
  initializeFirebase();
  const db = getFirestore();
  return db;
};

export const wipeDb = async () => {
  const db = getDb();
  const collections = await db.listCollections();
  const deletePromises = collections.map((collectionRef) =>
    db.recursiveDelete(collectionRef));

  Promise.all([...deletePromises]);
};

export const seed = async () => {
  const db = getDb();
  await db.collection('streamers').add({
    broadcasterId: '64522496',
    broadcasterName: 'ITonyl',
    color: '1565C0',
    description: 'Sr. Truchita',
    isOnline: false,
    puuid: 'kRQyIDe5TfLhWtn8jXgo_4Zjlfg4rPypXWiPCXrkTMUsiQT3TYVCkVO6Au3QTdd4x-13CbluPA53dg',
    summonerId: '9bnJOmLXDjX-sgPjn4ZN1_-f6m4Ojd2OWlNBzrdH0Xk2xw',
  });
  await db.collection('streamers').add({
    broadcasterId: '176444069',
    broadcasterName: 'Onokenn',
    color: '424242',
    description: 'El LVP Player',
    isOnline: false,
    puuid: 'Gbfj8FyB6OZewfXgAwvLGpkayA6xyevFfEW7UZdrzA6saKVTyntP4HxhBQFd_EIGa_P1xC9eVdy8sQ',
    summonerId: 'pPWUsvk_67FuF7ky1waWDM_gho-3NYP4enWTtte6deR3CjxOGoCfoIjjNw',
  });
};

export const resetDb = async () => {
  await wipeDb();
  await seed();
};

Sometimes I find that firestore has 4 records, other times it has 0 records, 2 records and so on.. I don't know why I await the promises before each test.有时我发现 firestore 有 4 条记录,有时它有 0 条记录、2 条记录等等。我不知道为什么我在每次测试之前等待承诺。

I expect to keep the same state before each test, can you help me please?我希望在每次测试之前保持相同的 state,你能帮帮我吗?

All the problem was the parallel behavior of jest, I just needed to run the tests sequentially with the param --runInBand or maxWorkers=1所有的问题都是 jest 的并行行为,我只需要使用参数--runInBandmaxWorkers=1顺序运行测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Jest 进行单元测试时出现“FIRESTORE 内部断言失败:意外状态” - 'FIRESTORE INTERNAL ASSERTION FAILED: Unexpected state' when unit testing with Jest 在本地测试 Cloud Functions 时 Cloud Firestore 模拟器未运行 - Cloud Firestore emulator not running when testing Cloud Functions locally 如何将 Firestore 侦听器功能部署到 GCP Cloud? - How to deploy Firestore listener functions to GCP Cloud? 如何从云功能中的 firestore 获取文档 - How to get a document from firestore in cloud functions 如何在 netlify lamda 中使用 firebase 云函数的 firestore.onWrite() - How to use firebase cloud functions' firestore.onWrite() in netlify lamda 如何通过Cloud Functions上传文件到Cloud Storage,并使用Firestore控制对Cloud Storage的访问? - How can I upload files to Cloud Storage through Cloud Functions and use Firestore to control access to Cloud Storage? Google Cloud Functions Firestore 限制 - Google Cloud Functions Firestore Limitations 如何从 Firestore 获取所有文档并进行循环(云功能) - how to get all documents from Firestore and make a loop (Cloud Functions) 如何使用 WebStorm 和 Ngrok 在本地运行 Firebase Firestore Cloud Functions 并对其进行调试? - How to run Firebase Firestore Cloud Functions locally and debuging it, with WebStorm and Ngrok? 如何使用 firebase 云函数对 Firestore 数据进行逻辑处理 - How to use firebase cloud functions for logic on firestore data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM