给定以下代码,我尝试测试ngOnChanges
Angular2 的生命周期钩子:
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 生命周期挂钩内进行测试,所以这不是我的解决方案。我也不想testComponent.ngOnChanges({someMockData});
直接调用测试。
如何TestComponent.value
从测试中设置它以便ngOnChanges
调用?