首页 > 解决方案 > Is it possible to mock an authenticated Firebase user, in order to run full testing with jest, while preserving the database rules?

问题描述

I have a Firebase Realtime Database set up with a bunch of basic rules revolving around basic user authentication:

{
  "rules": {
    ".read": false,
    ".write": false,
    "users": {
      "$user_id" : {
        ".read": "$user_id === auth.uid",
        ".write": "$user_id === auth.uid",
       }
    }
  }
}

These rules depend on the auth.uid built-in Firebase variable, which is accessible during development/production as a user is logged in with any given provider.

However, when I am running jest tests on a duplicated database with the same rules, I do not have access to this auth.uid since there is no actual user logged in.

Is there a way to solve this? A way to perhaps mock some sort of testing user on Firebase itself or through my client-side test code?

I would like the testing to run on a database that is as similar as possible to the regular database. I don't want to have a different rules structure on the test database.

标签: firebaseunit-testingtestingfirebase-realtime-databasejestjs

解决方案


我想出的可能解决方案更像是一种解决方法:

  1. 设置一个测试环境变量,如FIREBASE_TEST_UID.
  2. 运行测试时引用此 uid。
  3. 手动更改与实际存储的比较$user_id"规则auth.uidFIREBASE_TEST_UID
  4. 现在,数据库受到公共非“经过身份验证”用户的读写保护,而规则结构保持相似并且FIREBASE_TEST_UID是私有的(.gitignored env 文件)。

推荐阅读