在 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
Run Code Online (Sandbox Code Playgroud)
我已经分解了一些东西以找出导致错误的原因,很明显它是由组件中的表单引起的。如果我从 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
});
}
}
Run Code Online (Sandbox Code Playgroud)
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();
});
});
Run Code Online (Sandbox Code Playgroud)
我遇到了类似的事情,看起来也与 FormControls 相关。我通过将 NoopAnimationsModule 添加到我的 TestBed.configureTestingModule() 解决了这个问题。这可能不是您需要导入的确切模块,但它让我克服了这个错误。您肯定需要确保所有构造函数注入都在您的测试中得到考虑。
除了确保提供所有可注入项之外,您还需要确保所有服务模拟都已到位。例如,当我忽略添加与下面的“fetchthings: jest.fn()”模拟等效的内容时,我再次遇到了这个错误:
{ provide: MyService, useValue: { fetchThings: jest.fn() } }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2901 次 |
| 最近记录: |