spyObj withArgs模拟无法正常工作

时间:2018-12-09 12:28:19

标签: angular typescript karma-jasmine karma-runner angular-test

从上一个问题得到答案后,我尝试向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));不能像预期的那样工作?

0 个答案:

没有答案