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

Node.js测试中proxyquire引入模块取routes返回值的handler为undefined

问题修复方案

核心错误原因

你定义的routes方法返回值是数组类型,数组内部的第一个元素才是携带handler函数的目标对象。你直接对数组调用.handler属性,数组本身没有这个属性,所以返回undefined。
额外说明:routes方法没有异步逻辑,调用时不需要加await,当然加了也不会抛出错误,仅属于冗余写法。另外你原代码中调用chance.Number没有加执行括号,传入的是方法本身而非生成的随机数值,也会导致后续执行异常。

修正后的测试代码

/* Pulls in and libraries like chai, chai expect, chance, to, sinon, proxyquire, and sinonChai */
/* CODE */
describe ('function fetcher', () => {
  it('should return a function', async () => {
    let testModule = proxyquire('../path-to-file/', {})
    // 无异步逻辑可直接调用,也可保留await不影响执行
    let myObject =  testModule.routes() 
    console.debug(typeof(myObject))
    console.debug(myObject)
    // 取数组第一个元素的handler属性
    let result = myObject[0].handler
    console.debug(typeof(result))
    console.debug(result)
    // chance.Number是生成方法,需要加括号执行得到数值
    result(chance.Number(), chance.Number())
    /* More processing */
  })
})

修正后typeof(result)会输出function,可以正常执行return result(a, b)逻辑。

内容的提问来源于stack exchange,提问作者lilHar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:36:03