【问题标题】:Jest & Firebase Emulator - wait for trigger function to be calledJest & Firebase Emulator - 等待触发函数被调用
【发布时间】:2021-08-30 02:06:53
【问题描述】:

我的package.json 文件包含以下内容:

...
    "jest": "jest --runInBand",
    "test": "firebase emulators:exec 'npm run jest'"
...

这允许我使用正在运行的 Firebase 模拟器运行基于 jest 的测试。

考虑以下代码:

describe("MyTests", () => {
  const req = supertest(app);
  let user: admin.auth.UserRecord;
  let idToken: string | undefined;

  beforeAll(async () => {
    const email = "test@gmail.com";
    const password = "password";
    user = await admin.auth().createUser({ email: email, password: password });

    await auth.signInWithEmailAndPassword(email, password);
    idToken = await auth.currentUser?.getIdToken();
  });

// actual tests

我在哪里创建 Firebase 用户,该用户又会触发一个函数 (functions.auth.user().onCreate(foo))。

我确实注意到这个 foo 函数是在 开玩笑的测试套件运行之后执行的:

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        14.841 s, estimated 16 s
Ran all test suites.
✔  Script exited successfully (code 0)
i  functions: Beginning execution of "us-central1-foo"
i  emulators: Shutting down emulators.
i  functions: Stopping Functions Emulator
i  functions: Waiting for all functions to finish...
i  functions: Finished "us-central1-foo" in ~1s

如何等待它从 beforeAll() 函数内部执行?

【问题讨论】:

  • 您是如何找到解决方案的?
  • @Piotr 不,仍在等待帮助
  • 我的“解决方案”是等待 2.5 秒????

标签: firebase jestjs firebase-tools


【解决方案1】:

我找到了一个非常老套的解决方案来完成这项工作,但它确实有效。

当我自己研究这个问题时,我意识到来自模拟器 UI 的日志可以在ws://localhost:4500的 websocket 上找到

所以我所做的是我创建了一个函数,它根据 firebase 日志 Beginning execution of " 和 Finished " 检查函数何时开始以及函数何时结束

我还创建了一个函数,该函数添加了一个侦听器,当从上一个 Finished "-message 开始的 100 毫秒内没有触发任何函数时触发该侦听器

firebase emulators:exec-命令中默认不包含模拟器 UI,因此您需要使用 firebase emulators:exec --ui "npm test" 运行它才能启动日志服务。

我是这样用的

beforeAll(async () => {
  await initFirebaseListener()
})
afterAll(() => {
  closeSocket()
})

describe('wait for firebase', () => {
  test('should wait for firebase', async () => {
    // do stuff that triggers some auth, firestore, RTDB or whatever function
    await waitForFirebaseToFinish()
    // Get something that i can validate
    // expect(theThingIWasWaitingFor).toEqual('the expected value that the trigged did')
  })
})

要点:

  • 您需要关闭套接字才能在测试执行后终止进程
  • 这太hacky了,可以在firebase-admin的下一次更新中破解
  • 您需要在emulators:exec 命令中添加--ui 才能启动日志服务。
  • 至少对我来说有效。

使用代码创建了一个要点,链接如下。 我使用 websocket npm 库 (npm install -D websocket) 来订阅日志,但如果您愿意,可以使用其他库。

https://gist.github.com/Gurey/8301022f8357b3a7d74cefca4b598646

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 2019-06-28
    • 1970-01-01
    相关资源
    最近更新 更多