我正在尝试为我的代码编写集成测试。我想使用 Firebase Local Emulator 能够进行端到端测试并查看文档和集合是否正确更新。 为了了解模拟器的工作原理,我编写了一个示例触发器
exports.myItemAdder = functions.https.onCall(async (data, context) => {
if(!context.auth){
throw new functions.https.HttpsError('unauthenticated', 'Sign in');
}
try{
await db.doc('test-items/test-item').set({
name: data.name,
description: 'Learning to write Integration Tests'
});
}
catch(error){
throw new functions.https.HttpsError('unknown', error);
}
return 'Document Added'
});
这就是我的测试结果
describe('Calling myItemAdder adds another document', () => {
const db = firebase.initializeTestApp({ projectId: REAL_FIREBASE_PROJECT_ID, auth: aliceAuth }).firestore();
const functions = firebase.initializeTestApp({ projectId: REAL_FIREBASE_PROJECT_ID }).functions();
functions.useFunctionsEmulator("localhost:5001");
let myItemAdderFunc = functions.httpsCallable('myItemAdder')
after(() => {
firebase.clearFirestoreData({projectId: REAL_FIREBASE_PROJECT_ID});
});
it('Should return document added', async() => {
const result = await myItemAdderFunc({'name': 'Test'});
expect(result.data).to.equal('1Document Added'); // This should fail
});
});
但是当我使用
npm test
命令运行测试时,它给了我这个错误
Error: internal
at new HttpsErrorImpl (node_modules/@firebase/functions/dist/index.node.cjs.js:59:28)
at _errorForResponse (node_modules/@firebase/functions/dist/index.node.cjs.js:154:12)
at Service.<anonymous> (node_modules/@firebase/functions/dist/index.node.cjs.js:539:33)
at step (node_modules/@firebase/functions/node_modules/tslib/tslib.js:136:27)
at Object.next (node_modules/@firebase/functions/node_modules/tslib/tslib.js:117:57)
at fulfilled (node_modules/@firebase/functions/node_modules/tslib/tslib.js:107:62)
当我使用
firebase functions:shell
调用此函数时,它运行完美并将文档添加到 Firestore 的模拟版本中
我刚刚遇到了同样的错误。在调试并单步执行 Firebase 代码后,我意识到
useFunctionsEmulator
需要一个有效的原始 URL,包括一个方案。它的JSDoc给出了一个例子:
这是我的代码。另请注意调用
auth
中的 initializeTestApp
:它会传播到 request.auth
中的函数:
const firebase = require("@firebase/testing");
[...]
it("call helloWorld callable function", async () => {
const functions = firebase.initializeTestApp({ projectId: MY_PROJECT_ID, auth: { uid: "USER_1" } }).functions();
functions.useFunctionsEmulator("http://localhost:5001");
const helloWorld = functions.httpsCallable('callables-helloWorld');
const result = await helloWorld({ text: 'Hello!' });
assert.equal(result.data.hello, "world");
});