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

使用Jest测试Node.js child_process exec函数时遇类型错误求助

问题分析与解决建议

错误原因拆解

  1. 语法错误导致mock失效:exec.mockImplementation的回调函数末尾缺失闭合括号,mock未正确生效,exec调用后返回undefined,访问newSync.stdout时触发Cannot read properties of undefined (reading 'on')。
  2. 断言对象错误:测试中expect(exec.stdout.on).toHaveBeenCalled()逻辑错误——exec是被mock的函数,本身不存在stdout属性,stdout是exec调用返回对象的属性。

修正后的测试代码

const {randomFunc} = require('./randomFuncFile') // 替换为实际文件路径
const { exec } = require('child_process')
jest.mock('child_process')

it('test', () => {
    const readStreamObject = {
      on: jest.fn().mockImplementation(function (event, handler) {
        handler('streaming ')
      })
    }
    // 补上缺失的闭合括号,完成mock实现
    exec.mockImplementation(() => ({stdout: readStreamObject}))
    randomFunc()
    
    // 断言正确的mock函数:readStreamObject.on
    expect(readStreamObject.on).toHaveBeenCalledWith('data', expect.any(Function))
    // 额外验证exec是否被传入正确命令调用
    expect(exec).toHaveBeenCalledWith('some command to execute')
})

额外注意事项

  • 确认require(randomFuncFile)的路径为正确的相对路径,避免模块导入失败。
  • 若需测试console.log的输出,可添加对console.log的mock,验证它是否接收到'streaming '参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:21:00