使用Jest与Discord.js时出现Segmentation Fault,E2E测试失败
Discord.js + Jest E2E测试发送附件时触发Segmentation Fault错误
问题详情
- 技术栈:Node.js/NestJS + Jest + Discord.js
- 异常现象:开发阶段代码运行正常,但执行E2E测试时抛出段错误:
[1] 49780 segmentation fault npm run test:e2e - 触发条件:调用
channel.send({ 'content': 'xxx', 'files':[file] })时出错,仅发送content(无files参数)时测试可正常执行 - 涉及的AttachmentBuilder对象结构:
AttachmentBuilder { attachment: <Buffer ff... 510935 more bytes>, name: undefined, description: undefined
}
- 导入语句: ```javascript import { Client, Partials, Collection, GatewayIntentBits, TextChannel, AttachmentBuilder, MessageCreateOptions, EmbedBuilder } from 'discord.js';
- 已尝试操作:删除
node_modules后重新安装依赖 - 版本信息:
- node v18.12.1
- "jest": "^27.4.5"
- "discord.js": "^14.7.1"
可能的解决方案
1. 为AttachmentBuilder指定必填的name属性
从AttachmentBuilder的结构可以看到name为undefined,Discord.js处理附件时需要该字段标识文件名,开发环境可能有容错逻辑,但测试环境下未处理该情况导致内存错误。创建AttachmentBuilder时显式传入name:
const file = new AttachmentBuilder(yourBuffer, { name: 'example.png' }); // 根据文件类型替换扩展名
2. 禁用Jest的沙箱模式
Jest的沙箱机制可能与Discord.js处理Buffer或网络模拟的底层逻辑冲突,导致段错误。在jest-e2e.config.js中修改配置:
module.exports = { // 其他已有配置... testEnvironmentOptions: { sandbox: false } };
3. 升级Jest版本到兼容Node.js 18的版本
Jest 27.x与Node.js 18存在部分兼容性问题,升级到Jest 29.x可解决这类底层冲突:
npm install jest@^29.0.0 --save-dev
4. 在测试中Mock相关方法避免实际执行附件处理
E2E测试无需真的发送附件到Discord,用Jest Mock替换AttachmentBuilder和channel.send方法,跳过底层执行逻辑:
jest.mock('discord.js', () => { const original = jest.requireActual('discord.js'); return { ...original, AttachmentBuilder: jest.fn().mockReturnValue({ attachment: Buffer.from('test-content'), name: 'test-file.txt' }), TextChannel: jest.fn().mockImplementation(() => ({ send: jest.fn().mockResolvedValue({ id: 'mock-message-id' }) })) }; });
内容的提问来源于stack exchange,提问作者monkeyUser
相关产品推荐
相关产品推荐

