我想使用旁观者来帮助我进行单元测试,因为我已经阅读了有关它的精彩内容。但是我不确定如何解决我的测试问题。在我的组件模板中,我有一个formGroup
这样的......
<form [formGroup]="emailReportForm" (ngSubmit)="emailReport()">
<!-- Lots more HTML here -->
</form>
在我的 TS 文件中,我的ngOnInit
/ constructor
...
constructor(@Inject(MAT_DIALOG_DATA) data: any,
private formBuilder: FormBuilder,
private apiService: ApiService,
public dialogRef: MatDialogRef<EmailReportComponent>) {
this.data = data;
}
ngOnInit(): void {
this.emailReportForm = this.formBuilder.group({
emailAddress: new FormControl(null, [
Validators.required,
Validators.pattern('^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$')
]),
updateOn: 'keyup'
});
}
所以我需要模拟我的服务和导入,所以这是我的 spec.ts 文件......我减少了一些代码以提高可读性:
import { createComponentFactory, Spectator } from '#ng/node_modules/@ngneat/spectator/jest';
import { ApiService } from '#ng/src/app/common/services/api/api.service';
import { MAT_DIALOG_DATA, MatDialogRef } from '#ng/node_modules/@angular/material';
import { FormBuilder, FormControl, FormGroup, Validators,} from '#ng/node_modules/@angular/forms';
describe('EmailReportComponent', () => {
let spectator: Spectator<EmailReportComponent>;
const mockData = { };
const dialogMock = { close: () => { } };
const createComponent = createComponentFactory({
component: EmailReportComponent,
imports: [
FormBuilder,
FormControl,
FormGroup,
Validators,
],
componentProviders: [
{ provide: ApiService, useValue: { emailReport: jest.fn() } },
{ provide: MAT_DIALOG_DATA, useValue: mockData },
{ provide: MatDialogRef, useValue: dialogMock },
],
});
beforeEach(() => spectator = createComponent());
describe('Methods', () => {
// tests go here
});
当我运行测试时,出现以下错误:
错误:模块“DynamicTestModule”导入了意外的值“FormBuilder”。请添加 @NgModule 注释。
现在我可以用它CUSTOM_ELEMENTS_SCHEMA
来防止错误,但这似乎是错误的。谁能告诉我如何解决我的问题。