我已经在Angular 6
中写了我的第一个角度应用程序。
我还没有编写任何测试,但是在生成components
和services
时会自动创建一些默认的测试文件。
当我使用来运行自动生成的测试时
ng test
它给出了太多错误。其中一个错误是
ChangeAvatarModalComponent should create
Failed: Template parse errors:
There is no directive with "exportAs" set to "ngForm" ("
<div class="modal-body">
<form [formGroup]="changeAvatarForm" id="avatar-form" [ERROR ->]#formDir="ngForm" (submit)="onSubmit()">
<div class="row">
<div class="col-md-12">
"): ng:///DynamicTestModule/ChangeAvatarModalComponent.html@8:56
Can't bind to 'formGroup' since it isn't a known property of 'form'. ("
<div class="modal-body">
我有一个帐户模块,该模块具有 ChangeAvatarModalComponent 。
我在 account.module.ts
中包含以下几行@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
RouterModule.forChild(AccountRoutes),
NgbModule
],
declarations: [
ChangeAvatarModalComponent
],
entryComponents: [
ChangeAvatarModalComponent
]
})
export class AccountModule { }
以及FormsModule
和ReactiveFormsModule
也被导入到 app.module.ts
生成的日志中有很多此类错误。
编辑2:change-avatar-modal.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ChangeAvatarModalComponent } from './change-avatar-modal.component';
describe('ChangeAvatarModalComponent', () => {
let component: ChangeAvatarModalComponent;
let fixture: ComponentFixture<ChangeAvatarModalComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ChangeAvatarModalComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ChangeAvatarModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
答案 0 :(得分:1)
您没有在提供的代码中显示.spec.ts
文件。
出现表格问题的原因是,在规范文件中,您也需要导入相关模块,如下所示:
describe('ExampleComponent', () => {
let component: ExampleComponent
let fixture: ComponentFixture<ExampleComponent>
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
TranslateModule.forRoot({
loader: {provide: TranslateLoader, useClass: TranslateFakeLoader}
}),
HttpClientModule,
HttpClientTestingModule,
FormsModule,
SfFormModule,
ReactiveFormsModule,
NguiAutoCompleteModule,
NgxMyDatePickerModule,
NgxPermissionsModule.forRoot(),
PipeModule,
StoreModule.forRoot({}),
LayoutsModule
],
declarations: [
ExampleComponent
],
providers: [
{provide: APP_BASE_HREF, useValue: '/'},
{provide: ToastrService, MockToastrService},
ActionsSubject,
SimService
]
}).compileComponents()
}))
beforeEach(() => {
fixture = TestBed.createComponent(ExampleComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
在您的情况下,您需要在spec文件中导入FormsModule和/或ReactiveFormsModule,还可能要介绍其他内容。
为减少导入次数,您只需将自己的模块导入到规范文件中就可以摆脱困境-例如AccountModule和/或AppModule-因为它们已经导入了表单内容。