TypeError: stream.listeners is not a function含义及问题排查(Jest测Firebase云函数)
问题:Firebase onRequest云函数Jest单元测试报错
TypeError: stream.listeners is not a function 相关代码
测试代码
const index = require ('./index') describe ('test function', () => { it('positive case', async () => { let req = { "usn": "cmu2010"} let res = { "response": "hi cmu"} index.myCloudFunction(req, res) }); });
index.js文件
const admin = require('firebase-admin') admin.initializeApp(); const importFile = require('./myCloudFunction') exports.myCloudFunction = importFile.myCloudFunction
myCloudFunction.js文件
const functions = require ("firebase-functions") myCloudFunction.post("/", async(request, response) => { // 业务逻辑 }) exports.myCloudFunction = functions.https.onRequest(myCloudFunction)
运行上述测试时出现错误 TypeError: stream.listeners is not a function,请问该错误含义是什么?哪里出错了?
错误原因及解决方法
错误含义
这个错误说明测试代码传入的req和res对象不符合functions.https.onRequest期望的标准HTTP请求/响应对象格式,函数内部处理流相关逻辑时,尝试调用stream.listeners方法但失败——因为你自定义的普通对象根本没有这个方法。
核心出错点
- 请求响应对象过于简陋:你手动创建的
req、res只是简单键值对对象,缺少Express/Firebase云函数依赖的HTTP请求响应对象核心方法(比如res.send、req.body)和流相关接口。 - Express应用未初始化:
myCloudFunction.js中直接调用myCloudFunction.post,但未提前创建Express应用实例,这本身属于语法错误,会导致myCloudFunction变量未定义。
修复步骤
- 补全Express应用初始化:修改
myCloudFunction.js,先创建合法的Express实例:
const functions = require("firebase-functions"); const express = require("express"); const app = express(); app.use(express.json()); // 解析JSON请求体 app.post("/", async (request, response) => { const usn = request.body.usn; response.send(`hi ${usn}`); }); exports.myCloudFunction = functions.https.onRequest(app);
- 使用标准模拟对象替代自定义简单对象:
- 推荐用
supertest工具直接模拟HTTP请求,更贴合实际场景:const request = require('supertest'); const index = require('./index'); describe('test function', () => { it('positive case', async () => { await request(index.myCloudFunction) .post('/') .send({ usn: 'cmu2010' }) .expect(200) .expect('hi cmu2010'); }); }); - 若不想引入额外工具,也可手动模拟必要方法:
const index = require('./index'); describe('test function', () => { it('positive case', async () => { const req = { method: 'POST', body: { usn: 'cmu2010' }, on: jest.fn(), pipe: jest.fn() }; const res = { send: jest.fn().mockReturnThis(), status: jest.fn().mockReturnThis() }; await index.myCloudFunction(req, res); expect(res.send).toHaveBeenCalledWith('hi cmu2010'); }); });
- 推荐用
内容的提问来源于stack exchange,提问作者Renee
相关产品推荐
相关产品推荐

