[英]Firebase Cloud Function unit test HTTP onCall
我想为一堆云函数编写一些单元测试。 现在我面临以下问题。 使用firebase-functions-test
我不知何故无法测试 HTTP 触发的云功能。 以下是我想使用jest
测试的一些云功能:
export cloudFunctions = {
createUserByAdmin: functions.runWith({ timeoutSeconds: 30, memory: '256MB' }).https.onCall(UserService.createUserByAdmin),
updateUserByAdmin: functions.runWith({ timeoutSeconds: 30, memory: '256MB' }).https.onCall(UserService.updateUserByAdmin),
deleteUserByAdmin: functions.runWith({ timeoutSeconds: 30, memory: '256MB' }).https.onCall(UserService.deleteUserByAdmin)
}
它们都部署在 Firebase 上,并且可以正常工作。 但是我找不到使用firebase-functions-test
包调用的方法。 此外,还有一些关于如何使用该包编写单元测试的示例,但没有一个示例测试 http 触发的函数。
这是我的测试文件:
import * as functions from 'firebase-functions-test'
import * as admin from 'firebase-admin'
import * as path from 'path'
const projectConfig = {
projectId: 'test-fb',
}
const testEnv = functions(
projectConfig,
path.resolve('DO-NOT-EDIT.dev.fb-admin-sdk-key.json'),
)
describe('[Cloud Functions] User Service', () => {
let cloudFunctions
beforeAll(() => {
cloudFunctions = require('../index')
})
afterAll(() => {
// delete made accounts/entrys
})
describe('Testing "createUserByAdmin"', () => {
it('Creating User does work', () => {
expect(1).toBe(0)
})
})
})
有人知道如何测试http云功能吗? 我真的很感激一个例子。 谢谢!
我实际上找到了一种关于如何使用firebase-functions-test
测试 HTTP Cloud Functions 的方法,它可以与包装函数一起使用。 看看这个参考页面。 这里有一些代码可以让事情更清楚一些。
这是我的一个测试的片段
import * as functions from 'firebase-functions-test'
import * as admin from 'firebase-admin'
import * as path from 'path'
const projectConfig = {
projectId: 'myproject-id',
}
const testEnv = functions(
projectConfig,
path.resolve('fb-admin-sdk-key.json'),
)
// has to be after initializing functions
import * as cloudFunctions from '../index'
describe('Testing "createUserByAdmin"', () => {
const createUserByAdmin = testEnv.wrap(cloudFunctions.createUserByAdmin)
it('Creating User does work', async (done) => {
const data = {
displayName: 'Jest Unit Test',
email: 'unit@domain.com',
password: 'password',
uid: null,
}
const context = {
auth: {
token: {
access: 'somestring,
},
uid: 'mockuiddddd',
},
}
await createUserByAdmin(data, context)
.then(async (createdUser: any) => {
expect(createdUser.status).toBe('OK')
done()
})
.catch((error: any) => {
fail('createUserByAdmin failed with the following ' + error)
})
})
})
在使用我们的projectConfig
和我们的服务帐户密钥文件初始化我们的测试环境后,您会看到。
const testEnv = functions(
projectConfig,
path.resolve('fb-admin-sdk-key.json'),
)
您只需要使用.wrap()
函数包装适当的云函数。
const createUserByAdmin = testEnv.wrap(cloudFunctions.createUserByAdmin)
您可以像其他所有函数一样调用它(请记住,云函数通常需要一个数据参数(使用您在云函数中使用的变量)以及上下文参数,具体取决于您处理身份验证/授权的方式必须尝试错误才能找到您的函数请求的正确上下文属性。
如果您为生产云功能编写测试确保在运行测试后进行清理 - 例如删除创建的帐户或删除 firestore 或实时数据库中的数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.