【发布时间】:2020-12-02 04:58:54
【问题描述】:
在 Angular 项目中使用 Jest 运行测试时出现以下错误。
UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
| property 'element' -> object with constructor 'Object'
| property 'publicProviders' -> object with constructor 'Object'
| property 'ɵNgNoValidate_65' -> object with constructor 'Object'
--- property 'parent' closes the circle
我已经拆开来找出导致错误的原因,很明显它是由组件中的表单引起的。如果我从 FormGroup 中删除实际的 FormControls(表单域),那么测试运行没有问题。其他几种形式也是如此,我试过了。
我了解错误的含义,但不了解 FormControl 中导致该错误的原因。什么可能导致此错误?
@Component({
selector: 'app-edit-title-form',
template: `
<form (ngSubmit)="onSubmit()" [formGroup]="form" novalidate>
<input type="text" formControlName="title"> <!-- If this is removed then tests run -->
</form>
`
})
export class EditTitleFormComponent implements OnInit {
@Input() title: string = '';
@Output() onSave: EventEmitter<string> = new EventEmitter();
public form!: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit(): void {
this.initForm();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.title.currentValue) {
this.form.controls.title.setValue(changes.title.currentValue);
this.form.markAsPristine();
}
}
get field() {
return this.form.controls;
}
public onSubmit(): void {
this.onSave.emit(title);
}
private initForm(): void {
this.form = this.formBuilder.group({
title: [this.title, []], // If this line is removed along with the html input field, then tests run
});
}
}
describe('EditTitleFormComponent', () => {
let component: EditTitleFormComponent;
let fixture: ComponentFixture<EditTitleFormComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
ReactiveFormsModule,
],
declarations: [
EditTitleFormComponent,
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(EditTitleFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
【问题讨论】:
-
最近安装 npm 后,我遇到了同样的错误。您正在运行什么版本的 jest 和 jest-preset-angular?我在安装之前没有这个问题。
-
我们能够通过将 jest 更新为 26.1.0 并将 jest-preset-angular 更新为 8.2.1 来解决此问题。希望对您有所帮助!
-
我在使用 mat-table 测试组件时遇到了类似的错误。我更新到 @angular/common@10.0.10 (和其他相关包),之后它工作了。
-
这个@nicolaib 有什么更新吗?
-
尝试了上述所有解决方案,但对我不起作用。我正在运行 jest 版本 26.6.3、jest-preset-angular 版本 8.3.、@types/jest 版本 ^26.0.15 和 angular-common 版本 10.2.3