2017-07-14 93 views
-1

我在我們的Angular應用中實現了一個測試套件(Karma + Jasmine),但是我遇到了這個特定情況的問題。Angular + Jasmine:使用spyOn測試子組件的輸出

比方說,我需要測試一個名爲MessageComponent的組件,它發出一個按鈕的事件。如果我從父母測試它,我如何確保事件正確發射?

這裏的例子:

@Component({ 
    selector: "cw-message", 
    template: ` 
    <div #messageElement> 
     {{message.title}} 
     <button class="close icon" (click)="close($event, messageElement)">Close</button> 
    </div>` 
}) 
class MessageComponent { 

    @Input() message; 
    @Output() onClose:EventEmitter<boolean> = new EventEmitter(); 

    public close(event:Event, element:HTMLElement):void { 
     this.onClose.emit(true); 
    } 
} 

有這樣的分量,我想用下面的代碼進行測試:

describe("MessageComponent",() => { 

    let comp:TestComponent; 
    let fixture:ComponentFixture<TestComponent>; 
    let de:DebugElement; 

    @Component({ 
     template: ` 
     <div> 
      <cw-message class="first" [message]="message"></cw-message> 
     </div>` 
    }) 
    class TestComponent { 

     @ViewChild(MessageComponent) messageComponent:MessageComponent; 
     public message = { 
      title: "My message", 
      content: "The content of the message", 
      duration: 1000, 
     }; 

     ngAfterViewInit() {}; 

     ngAfterContentInit() {}; 

     ngAfterViewChecked() {} 

     ngAfterContentChecked() {}; 
    } 


    beforeEach(async(() => { 
     TestBed.configureTestingModule({ 
      imports: [ FormsModule ], 
      declarations: [ TestComponent, MessageComponent, ], 
     }).compileComponents(); 
    })); 

    beforeEach(() => { 
     fixture = TestBed.createComponent(TestComponent); 
     comp = fixture.componentInstance; 
     de = fixture.debugElement; 
     fixture.detectChanges(); 
    }); 

    fit("Should close message",() => { 

     spyOn(comp.messageComponent, "close"); 
     spyOn(comp.messageComponent.onClose, "emit"); 
     let messageDiv:HTMLElement = fixture.nativeElement.querySelector(".message"); 
     let closeBtn = fixture.nativeElement.querySelector(".close.icon"); 

     closeBtn.click(); 

     expect(comp.messageComponent.onClose.emit).toHaveBeenCalledWith(true); 
    }); 

}); 

但我始終有以下例外結束了:

Expected spy emit to have been called with [ true ] but it was never called.

這讓我思考......是否有可能通過這種方式來測試子組件?我究竟做錯了什麼?

+1

'comp.messageComponent.onClose.emit'永遠不會被調用,因爲您已經重寫了'comp.messageComponent'.close方法 – yurzui

+1

不需要父測試組件;實例化孩子,訂閱輸出字段然後觸發點擊事件。 – jonrsharpe

+0

@jonrsharpe這就是我所做的,但它拋出了相同的異常:'期望的間諜發出已被調用與[真],但它從來沒有被稱爲。' – user4068063

回答

0

您需要調用fixture.detectChanges();調用click方法後調用 。

相關問題