2

我正在我们的 Angular 应用程序中实现一个测试套件(Karma+Jasmine),但我遇到了这个特定案例的问题。

假设我需要测试一个名为 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.

这让我在想……甚至有可能以这种方式测试子组件吗?我究竟做错了什么?

4

1 回答 1

3

您需要调用 fixture.detectChanges(); 调用click方法后。

于 2017-08-17T12:19:16.807 回答