Angular使用Jest执行测试时报Converting circular structure to JSON错误如何解决?
Jest执行Angular测试报循环结构转JSON错误解决方案
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
| property 'element' -> object with constructor 'Object'
| property 'componentProvider' -> object with constructor 'Object'
--- property 'parent' closes the circle
at stringify ()
该错误是Jest运行Angular单元测试的高频问题,出现其他属性相关的变体报错本质原因一致,按以下步骤排查即可:
错误根源
Jest在做日志输出、断言比对、快照生成时,默认会调用JSON.stringify序列化目标对象,而Angular的ComponentFixture、DebugElement等测试对象内置了parent、element的双向引用,属于循环结构,原生JSON序列化不支持就会抛出该错误。
排查与解决方法
- 首先排查测试代码中是否存在直接打印测试对象的
console.log语句
调试时直接打印fixture、debugElement或者组件实例里挂载的DOM相关对象,未删除就会触发报错。如果需要保留日志,可使用Node内置的util.inspect处理循环引用:import * as util from 'util'; // 只打印前3层结构,避免遍历到循环引用 console.log(util.inspect(fixture.debugElement, { depth: 3 })); - 排查是否存在全量比对Angular测试对象的断言
不要直接用toEqual、toStrictEqual断言整个DebugElement、组件实例对象,只需要断言你需要校验的具体属性即可:// 错误写法:全量比对带循环引用的对象 expect(fixture.debugElement.query(By.css('.title'))).toEqual(expectedElement); // 正确写法:只断言目标属性 expect(fixture.debugElement.query(By.css('.title'))?.nativeElement.textContent).toContain('预期文本'); - 检查Jest配置是否添加了Angular专用序列化器
如果使用了快照测试,必须在Jest配置中添加jest-preset-angular提供的序列化器,避免快照生成时触发循环引用报错,参考jest.config.js配置:module.exports = { preset: 'jest-preset-angular', setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'], snapshotSerializers: [ 'jest-preset-angular/build/serializers/no-ng-attributes', 'jest-preset-angular/build/serializers/ng-snapshot', 'jest-preset-angular/build/serializers/html-comment' ] }; - 新增测试用例收尾销毁逻辑
多测试用例场景下,未销毁的fixture可能会残留跨用例的循环引用,在测试套的afterEach钩子中添加销毁逻辑:afterEach(() => { fixture.destroy(); });
内容的提问来源于stack exchange,提问作者BingeCode
相关产品推荐
相关产品推荐

