luk*_*knk 6 unit-testing firebase jestjs google-cloud-functions
我想为一堆云函数编写一些单元测试。现在我面临以下问题。使用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)
}
Run Code Online (Sandbox Code Playgroud)
它们都部署在 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)
})
})
})
Run Code Online (Sandbox Code Playgroud)
有人知道如何测试http云功能吗?我真的很感激一个例子。谢谢!
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: '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)
})
})
})
Run Code Online (Sandbox Code Playgroud)
使用我们的projectConfig服务帐户密钥文件初始化我们的测试环境后,您将看到这一点。
const testEnv = functions(
projectConfig,
path.resolve('fb-admin-sdk-key.json'),
)
Run Code Online (Sandbox Code Playgroud)
您只需使用该.wrap()函数包装适当的云函数即可。
const createUserByAdmin = testEnv.wrap(cloudFunctions.createUserByAdmin)
您可以像其他函数一样调用它(请记住,云函数通常需要一个数据参数(带有您在云函数中使用的变量)以及上下文参数,具体取决于您处理身份验证/授权的方式必须尝试和错误才能找到函数请求的正确上下文属性。
如果您为生产云功能编写测试,请确保在运行测试后进行清理 - 例如删除创建的帐户或删除 firestore 或实时数据库中的数据
| 归档时间: |
|
| 查看次数: |
2242 次 |
| 最近记录: |