监视 Angular5 组件无法正常工作

Spy on Angular5 component not working properly

我的组件具有以下功能:

  updateTransactions() {
    let notes = this.createNotes()

    let delTransactions = this.createDelTransactions()
    this.noteService.createNote(notes[0])
    this.noteService.getNoteCreated().subscribe((res) => {
      notes.shift();
      if(res && notes.length > 0) {
        this.noteService.createNote(notes[0])
      } else {
        this.deliverableTransactionService.updateDeliverableTransaction(delTransactions[0].id, delTransactions[0])
      }
    })

    this.deliverableTransactionService.getUpdateDeliverableTransactionStatus().subscribe((res) => {
      delTransactions.shift();
      if(res && delTransactions.length > 0) {
        this.deliverableTransactionService.updateDeliverableTransaction(delTransactions[0].id, delTransactions[0])
      } else {
        this.closeModal();
      }
    })
    console.log('current note', this.note)
  }

我的测试如下:

  it('should initialize properly when updating', () => {
    let testTransactions = [{id: 1}]
    let dueDate = '1/2/3'
    let testNote = 'Test'
    component.deliverableTransactions = testTransactions
    component.dueDate = dueDate
    component.note = testNote

    spyOn(component, 'createNotes').and.callThrough();
    spyOn(component, 'createDelTransactions').and.callThrough();
    spyOn(noteService, 'createNote').and.returnValue(true);
    spyOn(noteService, 'getNoteCreated').and.returnValue({subscribe: () => true});
    spyOn(deliverableTransactionService, 'getUpdateDeliverableTransactionStatus').and.returnValue({subscribe: () => true});

    component.updateTransactions();

    expect(component.createNotes).toHaveBeenCalled();
    expect(component.createDelTransactions).toHaveBeenCalled();
    expect(noteService.createNote).toHaveBeenCalled();
    expect(noteService.getNoteCreated).toHaveBeenCalled();
    expect(deliverableTransactionService.getUpdateDeliverableTransactionStatus).toHaveBeenCalled();
  })

我在以下位置定义了各种服务:

  beforeEach(async(() => {
    fixture = TestBed.createComponent(ChangeDueDateComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    deliverableTransactionService = TestBed.get(DeliverableTransactionService);
    noteService = TestBed.get(NoteService);
    activeModal = TestBed.get(NgbActiveModal);
  }));

然而,当我 运行 测试时,我得到一个错误:

PhantomJS 2.1.1 (Windows 7 0.0.0) ChangeDueDateComponent should initialize properly when updating FAILED
        Error: <spyOn> : getNoteCreated() method does not exist

我做错了什么?

您正在尝试 return 来自 getNoteValue 而不是 Observable 的订阅。

这样改变你的间谍 :

spyOn(noteService, 'getNoteCreated').and.returnValue(Observable.of(true));

我不知道为什么在 noteService 上找不到 getNoteCreated。它应该在那里吗?

无论如何,您可以通过以下方式创建间谍来避免错误:

noteService.getNoteCreated = jasmine.createSpy().and
  .returnValue({subscribe: () => true});