I get the following error when I run tests using Jest in an Angular project.
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
I have taken things apart to find what is causing the error and it is pretty clear that it is caused by the forms in the components. If I remove the actual FormControls (form fields) from the FormGroup, then the tests run without problems. The same happens with several other forms, I have tried.
I understand what the error means, but not what is causing it in the FormControl. What could cause this error?
@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();
});
});