你能为 Express Google Cloud Functions 编写测试吗?

Can you write tests for Express Google Cloud Functions?

我构建了一个 Cloud Function express API,我想知道如何为它编写测试。

回答您的问题:当然,您可以为Google Cloud Functions 编写测试。我还要补充一点,就像任何其他应用程序一样,您应该 编写测试。

你可以看看 Cloud Functions documentation about Testing and CI/CD. In the Node.js part, it shows how to test Cloud Functions with Mocha as a test framework and Sinon 作为模拟框架。测试过程应该是您本地开发和 CI 工具的一部分,如果您有的话。

基本上,有 3 种类型的测试:

  • 单元测试
  • 集成测试
  • 系统测试

单元测试中,您应该模拟 HTTP 框架 (Express) 以测试代码的一小部分。

集成测试中,你应该模拟你的函数和其他组件之间的任何外部依赖(例如,如果你的Function 将数据写入 Cloud SQL 数据库,那么你应该 mock 这个 Cloud SQL 数据库)。

系统测试中,您应该将函数部署到特定的 GCP 环境(很可能是一个独立的项目),以确保您的函数与其他 GCP 组件交互良好,或者在您触发它时启动。

最后,之前有一个 Cloud Functions Node.js emulator to locally test Functions. This have been deprecated, but replaced by the Functions Framework,也可用于“启动本地开发服务器以进行快速测试”。