gpt4 book ai didi

Firebase 云功能单元测试 HTTP onCall

转载 作者:行者123 更新时间:2023-12-04 12:58:07 25 4
gpt4 key购买 nike

我想为一堆云函数编写一些单元测试。现在我面临以下问题。使用 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 云函数的方法这一切都适用于包装函数。看看这个reference page .这里有一些代码可以让事情更清楚一些。
这是我的一个测试的片段

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 初始化我们的测试环境后,您会看到。和我们的服务帐户 key 文件。
const testEnv = functions(
projectConfig,
path.resolve('fb-admin-sdk-key.json'),
)
你只需要用 .wrap() 包装适当的云函数功能。 const createUserByAdmin = testEnv.wrap(cloudFunctions.createUserByAdmin)您可以像其他所有函数一样调用它(请记住,云函数通常需要一个数据参数(使用您在云函数中使用的变量)以及上下文参数,具体取决于您处理身份验证/授权的方式必须尝试错误才能找到您的函数请求的正确上下文属性。
如果您为生产云功能编写测试确保在运行测试后进行清理 - 例如删除创建的帐户或删除 firestore 或实时数据库中的数据

关于Firebase 云功能单元测试 HTTP onCall,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63577475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com