angular - 在 Angular 2 中测试 ngOnChanges 生命周期钩子(Hook)

标签 angular karma-jasmine angular2-components angular2-testing

给定以下代码,我尝试测试 Angular2 的 ngOnChanges 生命周期钩子(Hook):

import {
    it,
    inject,
    fdescribe,
    beforeEachProviders,
} from '@angular/core/testing';

import {TestComponentBuilder} from '@angular/compiler/testing';

import {Component, OnChanges, Input} from '@angular/core';

@Component({
    selector: 'test',
    template: `<p>{{value}}</p>`,
})
export class TestComponent implements OnChanges {
    @Input() value: string;

    ngOnChanges(changes: {}): any {
        // should be called
    }
}

fdescribe('TestComponent', () => {
    let tcb: TestComponentBuilder;

    beforeEachProviders(() => [
        TestComponentBuilder,
        TestComponent,
    ]);

    beforeEach(inject([TestComponentBuilder], _tcb => {
        tcb = _tcb;
    }));

    it('should call ngOnChanges', done => {
        tcb.createAsync(TestComponent).then(fixture => {
            let testComponent: TestComponent = fixture.componentInstance;

            spyOn(testComponent, 'ngOnChanges').and.callThrough();

            testComponent.value = 'Test';
            fixture.detectChanges();

            expect(testComponent.ngOnChanges).toHaveBeenCalled();
            done();
        }).catch(e => done.fail(e));
    });
});

不幸的是,测试失败并显示消息 Expected spy ngOnChanges to have been called. 我知道我可以在这个例子中检查 HTML 元素的内容,但我有一些代码需要在 ngOnChanes 生命周期 Hook 内部进行测试,所以这对我来说不是解决方案。我也不想在测试中直接调用 testComponent.ngOnChanges({someMockData});

如何设置测试中的 TestComponent.value 以便调用 ngOnChanges

最佳答案

我想我参加聚会有点晚了,但这可能对将来的某些人有用。

自 Angular 的 RC 5 发布以来,测试发生了一些变化。然而,这里的主要问题是当以编程方式设置输入时,不会调用 ngOnChangesSee this for more info .基本上,OnChanges Hook 仅在通过 View 传递输入时触发

对此的解决方案是让主机组件成为测试组件的父组件,并通过主机组件的模板传递输入。

这是完整的工作代码:

import {Component, OnChanges, Input, ViewChild} from '@angular/core';
import { TestBed }      from '@angular/core/testing';

@Component({
    selector: 'test',
    template: `<p>{{value}}</p>`,
})
export class TestComponent implements OnChanges {
    @Input() value: string;

    ngOnChanges(changes: {}): any {
        // should be called
    }
}
/* In the host component's template we will pass the inputs to the actual
 * component to test, that is TestComponent in this case
 */
@Component({
    selector : `test-host-component`,
    template :
    `<div><test [value]="valueFromHost"></test></div>`
})
export class TestHostComponent {
    @ViewChild(TestComponent) /* using viewChild we get access to the TestComponent which is a child of TestHostComponent */
    public testComponent: any;
    public valueFromHost: string; /* this is the variable which is passed as input to the TestComponent */
}

describe('TestComponent', () => {

    beforeEach(() => {
        TestBed.configureTestingModule({declarations: [TestComponent,TestHostComponent]}); /* We declare both the components as part of the testing module */
    });

    it('should call ngOnChanges', ()=> {
        const fixture = TestBed.createComponent(TestHostComponent);
        const hostComponent = fixture.componentInstance;
        hostComponent.valueFromHost = 'Test';
        const component = hostComponent.testComponent;
        spyOn(component, 'ngOnChanges').and.callThrough();
        fixture.detectChanges();
        expect(component.ngOnChanges).toHaveBeenCalled();
    })


});

关于angular - 在 Angular 2 中测试 ngOnChanges 生命周期钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37408801/

相关文章:

根中的Angular2动态组件注入(inject)

typescript - 如何隐藏和替换 Angular2 中的组件

angular - 如何在 Angular4 中使用 Karma-Jasmine 测试导出功能

javascript - Nock 不拦截 http 请求

javascript - 通过 NGRX 显示成功、错误消息的正确方法

angular - 发布请求有效但 Put 请求不在 Angular 2

angularjs - 通过右键菜单在 Web Storm 中运行单个 Karma Jasmine 测试

angular - 兄弟组件之间如何通信

angular - ESRI 加载程序搜索小部件聚焦 angular 7 的问题

angular - 使用 ngx-leaflet、HTTPClient 和 Angular2+ 将 GeoJSON 数据获取到 Leaflet map