You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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方法但失败——因为你自定义的普通对象根本没有这个方法。

核心出错点

  1. 请求响应对象过于简陋:你手动创建的req、res只是简单键值对对象,缺少Express/Firebase云函数依赖的HTTP请求响应对象核心方法(比如res.send、req.body)和流相关接口。
  2. Express应用未初始化:myCloudFunction.js中直接调用myCloudFunction.post,但未提前创建Express应用实例,这本身属于语法错误,会导致myCloudFunction变量未定义。

修复步骤

  1. 补全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);
  1. 使用标准模拟对象替代自定义简单对象:
    • 推荐用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 17:50:21