Jest 29.7自定义快照序列化器报错:TypeError读取plugins失败
Jest 29.7自定义快照序列化器报
TypeError: Cannot read properties of undefined (reading 'plugins')的解决办法 问题场景
严格遵循Jest官方文档编写的自定义快照序列化器代码,在Jest 29.7版本执行测试时,抛出TypeError: Cannot read properties of undefined (reading 'plugins')错误。
复现代码
自定义序列化器文件(如foo-serializer.js)
module.exports = { serialize(val, config, indentation, depth, refs, printer) { return `Pretty foo: ${printer(val.foo)}`; }, test(val) { return val && Object.prototype.hasOwnProperty.call(val, 'foo'); }, };
测试文件
test(() => { const bar = { foo: { x: 1, y: 2, }, }; expect(bar).toMatchSnapshot(); });
原因分析
Jest 29.x版本对快照序列化器的printer函数参数要求进行了变更,旧版本示例仅传递序列化目标值,而Jest 29需要传递完整的参数列表,否则内部插件系统无法正确初始化,导致抛出plugins读取错误。
解决方案
修改自定义序列化器的serialize方法,将所有必要参数传递给printer函数:
module.exports = { serialize(val, config, indentation, depth, refs, printer) { // 传递完整参数给printer,确保内部逻辑正常运行 return `Pretty foo: ${printer(val.foo, config, indentation, depth, refs)}`; }, test(val) { return val && Object.prototype.hasOwnProperty.call(val, 'foo'); }, };
同时确保在Jest配置文件中正确注册该序列化器:
// jest.config.js module.exports = { snapshotSerializers: ['./foo-serializer.js'], };
完成上述修改后,重新运行测试即可解决该错误。
内容的提问来源于stack exchange,提问作者alfredopacino
相关产品推荐
相关产品推荐

