间谍Angular5组件无法正常工作

问题描述 投票:1回答:2

我的组件具有以下功能:

  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

我做错了什么?

javascript angular unit-testing jasmine spy
2个回答
1
投票

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

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

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

0
投票

您正在尝试从getNoteValue而不是Observable返回订阅。

以这种方式改变你的间谍:

spyOn(noteService, 'getNoteCreated').and.returnValue(Observable.of(true));
© www.soinside.com 2019 - 2024. All rights reserved.