Angular DebugElement在我的角度测试示例中未按预期工作
我正在尝试向中添加一些测试代码Angular DebugElement在我的角度测试示例中未按预期工作,angular,typescript,jasmine,Angular,Typescript,Jasmine,我正在尝试向中添加一些测试代码 PostFormComponent包括一个input绑定和output事件发射器 @Component({ selector: 'app-post-form', templateUrl: './post-form.component.html', styleUrls: ['./post-form.component.css'] }) export class PostFormComponent implements OnInit, OnDestroy
PostFormComponent
包括一个input
绑定和output
事件发射器
@Component({
selector: 'app-post-form',
templateUrl: './post-form.component.html',
styleUrls: ['./post-form.component.css']
})
export class PostFormComponent implements OnInit, OnDestroy {
@Input() post: Post = { title: '', content: '' };
@Output() saved: EventEmitter<boolean> = new EventEmitter<boolean>();
sub: Subscription;
constructor(private postService: PostService) {}
submit() {
const _body = { title: this.post.title, content: this.post.content };
if (this.post.id) {
this.postService.updatePost(this.post.id, _body).subscribe(
data => {
this.saved.emit(true);
},
error => {
this.saved.emit(false);
}
);
} else {
this.postService.savePost(_body).subscribe(
data => {
this.saved.emit(true);
},
error => {
this.saved.emit(false);
}
);
}
}
ngOnInit() {
console.log('calling ngOnInit::PostFormComponent...');
}
ngOnDestroy() {
console.log('calling ngOnDestroy::PostFormComponent...');
if (this.sub) {
this.sub.unsubscribe();
}
}
}
@组件({
选择器:“应用程序发布表单”,
templateUrl:'./post form.component.html',
样式URL:['./post-form.component.css']
})
导出类PostFormComponent实现OnInit、OnDestroy{
@Input()post:post={title:'',content:''};
@输出()已保存:EventEmitter=新的EventEmitter();
分:认购;
构造器(私人邮政服务:邮政服务){}
提交(){
const_body={title:this.post.title,content:this.post.content};
if(此post.id){
this.postService.updatePost(this.post.id,_body).subscribe(
数据=>{
this.saved.emit(true);
},
错误=>{
this.saved.emit(false);
}
);
}否则{
this.postService.savePost(_body).subscribe(
数据=>{
this.saved.emit(true);
},
错误=>{
this.saved.emit(false);
}
);
}
}
恩戈尼尼特(){
log('calling ngOnInit::PostFormComponent…');
}
恩贡德斯特罗(){
log('callingngondestory::PostFormComponent…');
如果(本节){
此.sub.取消订阅();
}
}
}
组件模板:
<form id="form" #f="ngForm" name="form" class="form" (ngSubmit)="submit()">
<p>
<mat-form-field fxFlex>
<input matInput
id="title"
name="title"
#title="ngModel"
[(ngModel)]="post.title"
required/>
<mat-error align="start" *ngIf="title.hasError('required')">
Post Title is required
</mat-error>
</mat-form-field>
</p>
<p>
<mat-form-field fxFlex>
<textarea matInput
#content="ngModel"
name="content"
id="content"
[(ngModel)]="post.content"
rows="8"
required
minlength="10">
</textarea>
<mat-error align="start" *ngIf="content.hasError('required')">
Post Content is required
</mat-error>
<mat-error align="start" *ngIf="content.hasError('minlength')">
At least 10 chars
</mat-error>
</mat-form-field>
</p>
<p>
<button mat-button mat-raised-button color="primary" type="submit" [disabled]="f.invalid || f.pending"> {{'save'}}</button>
</p>
</form>
职位名称是必需的
帖子内容是必需的
至少10个字符
{{'save'}}
我试图为这个组件添加一些测试
describe('Component: PostFormComponent(input & output)', () => {
let component: PostFormComponent;
let fixture: ComponentFixture<PostFormComponent>;
let componentDe: DebugElement;
let savePostSpy: jasmine.Spy;
// Create a fake service object with spies
const postServiceSpy = jasmine.createSpyObj('PostService', [
'savePost',
'updatePost'
]);
beforeEach(() => {
TestBed.configureTestingModule({
imports: [BrowserAnimationsModule, SharedModule],
declarations: [PostFormComponent],
// provide the component-under-test and dependent service
providers: [
// { provide: ComponentFixtureAutoDetect, useValue: true },
{ provide: PostService, useValue: postServiceSpy }
]
}).compileComponents();
fixture = TestBed.createComponent(PostFormComponent);
component = fixture.componentInstance;
componentDe = fixture.debugElement;
fixture.detectChanges();
});
it('should raise `saved` event when the form is submitted (triggerEventHandler)', fakeAsync(() => {
const formData = { title: 'Test title', content: 'Test content' };
// trigger initial data binding
component.post = formData;
let saved = false;
savePostSpy = postServiceSpy.savePost
.withArgs(formData)
.and.returnValue(of({}));
// Make the spy return a synchronous Observable with the test data
component.saved.subscribe((data: boolean) => (saved = data));
// componentDe.triggerEventHandler('submit', null);
component.submit();
tick();
fixture.detectChanges();
expect(saved).toBeTruthy();
expect(savePostSpy.calls.count()).toBe(1, 'savePost called');
}));
});
description('Component:PostFormComponent(输入和输出)'),()=>{
let组件:PostFormComponent;
let夹具:组件夹具;
let componentDe:DebugElement;
让我们来侦察:茉莉。间谍;
//用间谍创建一个假的服务对象
const postServiceSpy=jasmine.createSpyObj('PostService'[
“储蓄邮政”,
“updatePost”
]);
在每个之前(()=>{
TestBed.configureTestingModule({
导入:[浏览动画模块,共享模块],
声明:[PostFormComponent],
//提供被测部件和相关服务
供应商:[
//{提供:ComponentFixtureAutoDetect,useValue:true},
{提供:PostService,useValue:postServiceSpy}
]
}).compileComponents();
fixture=TestBed.createComponent(PostFormComponent);
组件=fixture.componentInstance;
componentDe=fixture.debugElement;
fixture.detectChanges();
});
它('提交表单时应引发'saved'事件(triggerEventHandler)',fakeAsync(()=>{
const formData={title:'Test title',content:'Test content'};
//触发初始数据绑定
component.post=formData;
让保存=假;
savePostSpy=postServiceSpy.savePost
.withArgs(formData)
.和.returnValue(of({}));
//使spy返回与测试数据同步的可观测值
component.saved.subscribe((数据:布尔)=>(saved=data));
//组件de.triggerEventHandler('submit',null);
component.submit();
勾选();
fixture.detectChanges();
expect(已保存)。toBeTruthy();
expect(savePostSpy.calls.count()).toBe(1,'savePost called');
}));
});
问题是如果我使用
componentDe.triggerEventHandler('submit',null)
,测试将失败。但是调用component.submit()
效果很好。您希望触发表单上的提交事件,而不是整个组件,因此首先使用查询隔离表单元素:
const formElement = componentDe.query(By.css('form#form'));
formElement.triggerEventHandler('submit', null);
您希望触发表单上的提交事件,而不是整个组件,因此首先使用查询隔离表单元素:
const formElement = componentDe.query(By.css('form#form'));
formElement.triggerEventHandler('submit', null);
我认为你应该点击sumit按钮来触发事件
let submitButtonEL: DebugElement = fixture.debugElement.query(By.css('button'));
submitButtonEL.nativeElement.click()
使用form.triggerEventHandler('submit',null)直接触发表单的submitevent代码>并不能真正保证有一个UI方式来触发事件。
编写一个测试,单击submitbutton,然后检查submitevent fired是否保证它我认为应该通过单击sumit按钮触发事件
let submitButtonEL: DebugElement = fixture.debugElement.query(By.css('button'));
submitButtonEL.nativeElement.click()
使用form.triggerEventHandler('submit',null)直接触发表单的submitevent代码>并不能真正保证有一个UI方式来触发事件。
编写一个测试,单击submitbutton,然后检查submitevent fired是否保证了它