typescript - 在模擬器中測試 firestore 規則失敗,原因:JSON 在位置 0 發生意外的符號 <
我正在嘗試為我的 Firestore 規則設置單元測試。
由於我正在使用 TypeScript 和 Jest 進行測試,我試著編輯這個範例,但似乎我漏掉了什麼。
這是我的檔案:
import { readFileSync } from 'fs-extra'
import * as firebase from '@firebase/rules-unit-testing'
import { getDoc, setDoc, setLogLevel } from 'firebase/firestore'
describe('Firestore Rules', () => {
let testEnv: firebase.RulesTestEnvironment;
beforeAll(async () => {
testEnv = await firebase.initializeTestEnvironment({
firestore: { rules: readFileSync('../firestore.rules', 'utf8') },
projectId: 'myproject',
hub: { host: 'localhost', port: 4000 },
});
});
afterAll(async () => {
await testEnv.cleanup();
});
beforeEach(async () => {
await testEnv.clearFirestore();
});
test('noone should have access to user document', async function () {
// Setup: Create documents in DB for testing (bypassing Security Rules).
await testEnv.withSecurityRulesDisabled(async (context) => {
const testdoc = context.firestore().collection('users').doc('user1234');
await setDoc(testdoc, { test: 'test1' });
});
const unauthedDb = testEnv.unauthenticatedContext().firestore();
// Then test security rules by trying to read it using the client SDK.
const testdoc = unauthedDb.collection('users').doc('user1234');
await firebase.assertFails(getDoc(testdoc));
});
});
這是我的規則檔案:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if false;
}
}
}
當我嘗試運行測試時,我收到此錯誤:
FAIL src/tests/rules.test.ts
● Firestore Rules › noone should have access to user document
FetchError: invalid json response body at http://localhost:4000/emulators reason: Unexpected token < in JSON at position 0
at node_modules/@firebase/rules-unit-testing/node_modules/node-fetch/lib/index.js:272:32
那我到底做錯了什麼?