使用Jest测试Node.js child_process exec函数时遇类型错误求助
问题分析与解决建议
错误原因拆解
- 语法错误导致mock失效:
exec.mockImplementation的回调函数末尾缺失闭合括号,mock未正确生效,exec调用后返回undefined,访问newSync.stdout时触发Cannot read properties of undefined (reading 'on')。 - 断言对象错误:测试中
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
相关产品推荐
相关产品推荐

