[英]Bypassing Firestore Security Rules in jest tests
目前從事 React/Typescript/Firebase Firestore 項目。 在為從 UI 調用的某些操作/函數編寫 Jest 測試時,我遇到了以下問題:
在測試文件中,我可以使用 v9 api 設置 firestore 客戶端並使其與模擬器對話
const app = initializeApp(config.firebase);
const firestore = getFirestore(app);
connectFirestoreEmulator(firestore, "localhost", 8080);
此外,我還發現了如何設置管理客戶端並使其與模擬器對話
process.env.FIRESTORE_EMULATOR_HOST = "localhost:8080";
const serviceAccount = require("../../../my-key.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
...config.firebase
});
測試本身看起來像這樣:
describe("createCompanyAndRating action", () => {
test("call createCompanyAndRating and make sure it creates a proper rating entity", async () => {
// omitted: set testRatingFormState and other test data that are passed as args and
// pass in the firestore db client
const {
ratingId,
companyId,
} = await createCompanyAndRating({
ratingFormState: testRatingFormState,
visitorId: testVisitorId,
firestore,
});
// verify result by fetching the rating entity from the emulator db using the admin client
const ratingPath = `companies/${companyId}/ratings/${ratingId}`;
const ratingSnap = await admin.firestore().doc(ratingPath).withConverter(ratingConverter).get();
const rating: Rating | undefined = ratingSnap.data();
// omitted: verify result with some Jest expect-statetments...
});
})
我現在的問題是 Firestore 安全規則適用,並且只有經過身份驗證的用戶才能在 createCompanyAndRating 函數中使用的集合中編寫文檔,因此在調用該函數時測試已經拋出錯誤。
在這種情況下,我對測試安全規則本身不感興趣。
另外,請注意,我不能將管理客戶端傳遞給 createCompanyAndRating 函數,因為管理客戶端 API 與我在 createCompanyAndRating 函數實現中依賴的 v9 firebase API 不同(嘗試過但沒有用不僅是因為一些類型錯誤的方式)。
也許我的整個方法有點誤導,我寧願專注於測試 createCompanyAndRating 函數的內部,在那里我做了很多可以在沒有數據庫交互的情況下測試的工廠東西。
無論如何,非常感謝任何幫助/指導。
感謝您確認我找對了地方(即@firebase/rules-unit-testing)。 終於弄清楚了問題所在,錯過了 createCompanyAndRating 中的“等待”,所以 firestore 管理實例沒有獲取數據(我雖然這是一個管理配置問題......)謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.