从上一个问题得到答案后,我尝试向my sample添加更多测试。
savePost
模拟程序工作正常,但是我尝试测试updatePost
路径,但失败了。
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();
}
}
}
我的测试是:
it('should raise `saved` event when the form is submitted (triggerEventHandler):update', fakeAsync(() => {
const formData: Post = {
id: '1',
title: 'Test title',
content: 'Test content'
};
// trigger initial data binding
component.post = formData;
let saved = false;
// Make the spy return a synchronous Observable with the test data
updatePostSpy = postServiceSpy.updatePost
.withArgs('1', formData)
.and.returnValue(of({}));
component.saved.subscribe((data: boolean) => (saved = data));
// componentDe.triggerEventHandler('submit', null);
const formElement = componentDe.query(By.css('form#form'));
formElement.triggerEventHandler('submit', null);
// component.submit();
tick();
fixture.detectChanges();
expect(saved).toBeTruthy();
expect(updatePostSpy.calls.count()).toBe(1, 'updatePost called');
}));
似乎saved
的值未按预期分配。当我注释掉expect(saved).toBeTruthy()
时,expect(updatePostSpy.calls.count()).toBe(1, 'updatePost called')
有效,这意味着调用了updatePost
间谍,但是为什么component.saved.subscribe((data: boolean) => (saved = data));
不能像预期的那样工作?