使用Mocha测试Google Cloud Functions时报错:未找到测试文件
解决TypeScript编写Firebase Cloud Functions测试时Mocha提示"No test files found"的问题
问题背景
按照Firebase官方文档进行Cloud Functions单元测试时,进入functions目录执行npm run test,终端返回错误:
test
mocha --reporter specError: No test files found
项目使用TypeScript编写生产代码和测试代码,官方文档仅覆盖JavaScript场景,但已能正常通过应用调用函数、使用模拟器套件,仅测试环节出现问题。
示例生产函数:
import { Request, Response } from 'express'; export const helloWorld = (req: Request, res: Response) => { res.send('Hello, World!'); };
示例测试代码:
// use your actual details const test = require('firebase-functions-test')({ databaseURL: 'https://my-project.firebaseio.com', storageBucket: 'my-project.appspot.com', projectId: 'my-project', }, 'path/to/serviceAccountKey.json'); import * as mocha from "mocha"; import * as chai from "chai"; // be sure to only do this after initializing firebase-functions-test, and mocking config values. import * as functions from "../src/index"; import { Request, Response } from 'express'; describe('helloWorld function', () => { it('should send "Hello, World!"', () => { const req = {} as Request; const res = { send: (message: string) => { chai.expect(message).to.equal('Hello, World!'); } } as Response; functions.helloWorld(req, res); }); });
核心原因
Mocha默认仅识别JavaScript文件,不会自动解析TypeScript文件;同时默认的测试文件查找路径/命名规则与TypeScript项目结构不匹配。
解决方案
1. 安装TypeScript测试依赖
执行命令安装必要工具和类型定义:
npm install --save-dev ts-node typescript @types/mocha @types/chai
2. 修改package.json的test脚本
将原测试命令替换为:
{ "scripts": { "test": "mocha -r ts-node/register test/**/*.ts --reporter spec" } }
-r ts-node/register:让Mocha通过ts-node解析TypeScript文件test/**/*.ts:指定Mocha查找test目录下所有子目录的.ts测试文件(可根据命名习惯调整,比如test/**/*.test.ts匹配带.test后缀的测试文件)
3. 配置tsconfig.json包含测试文件
确保tsconfig.json的include字段覆盖测试目录,让TypeScript能编译测试文件:
{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "outDir": "./lib", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*", "test/**/*"], "exclude": ["node_modules"] }
4. 统一测试文件导入风格
测试文件中混合require和import易引发编译冲突,建议统一为ES模块风格:
import * as test from 'firebase-functions-test'; const testInstance = test({ databaseURL: 'https://my-project.firebaseio.com', storageBucket: 'my-project.appspot.com', projectId: 'my-project', }, 'path/to/serviceAccountKey.json'); import * as chai from "chai"; import * as functions from "../src/index"; import { Request, Response } from 'express'; describe('helloWorld function', () => { it('should send "Hello, World!"', () => { const req = {} as Request; const res = { send: (message: string) => { chai.expect(message).to.equal('Hello, World!'); } } as Response; functions.helloWorld(req, res); }); });
5. 确认测试文件路径与命名
确保测试文件放在test目录下,命名匹配test脚本中指定的规则(比如脚本用test/**/*.test.ts,测试文件就要命名为xxx.test.ts)。
验证操作
完成上述配置后,重新执行npm run test,Mocha即可正常找到并运行测试用例。
内容的提问来源于stack exchange,提问作者Filippo
相关产品推荐
相关产品推荐

