在我从上一个问题得到答案后,我试图为my sample添加更多测试 .

savePost 模拟效果很好,但我尝试测试 updatePost 路径,它失败了 .

PostFormComponent 包含 input 绑定和 output 事件 Launcher .

@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 Spy ,但是为什么 component.saved.subscribe((data: boolean) => (saved = data)); 不能用作expted?