在 Angular 2 中测试 ngOnChanges 生命周期挂钩
Testing ngOnChanges lifecycle hook in Angular 2
鉴于以下代码,我尝试测试 Angular2 的 ngOnChanges
生命周期钩子:
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
?
我想我来晚了一点,不过这可能对将来的某些人有用。
自 angular 的 RC 5 发布以来,测试发生了一些变化。然而,这里的主要问题是 ngOnChanges
在以编程方式设置输入时不会被调用。 See this for more info。基本上 OnChanges
钩子被触发 当输入仅通过视图传递时 .
这个问题的解决方案是让主机组件成为测试组件的父组件,并通过主机组件的模板传递输入。
这是完整的工作代码:
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();
})
});
您还可以选择手动调用 ngOnChanges
挂钩并在那里传递所需的更改对象。但是这并没有设置组件属性,只是调用了变化逻辑。
const previousValue = moment('2016-03-01T01:00:00Z');
const currentValue = moment('2016-02-28T01:00:00Z');
const changesObj: SimpleChanges = {
prop1: new SimpleChange(previousValue, currentValue),
};
component.ngOnChanges(changesObj);
请注意,此方法可以很好地测试 ngOnChanges
内部的逻辑,但它不会测试 @Input
装饰器是否已正确设置。
在Angular 4、测试时要手动触发ngOnChanges()
,需要手动调用(上面已经指出),只需要匹配new call signature of SimpleChange():
let prev_value = 'old';
let new_value = 'new';
let is_first_change: boolean = false;
component.ngOnChanges({
prop1: new SimpleChange(prev_value, new_value, is_first_change),
});
鉴于以下代码,我尝试测试 Angular2 的 ngOnChanges
生命周期钩子:
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
?
我想我来晚了一点,不过这可能对将来的某些人有用。
自 angular 的 RC 5 发布以来,测试发生了一些变化。然而,这里的主要问题是 ngOnChanges
在以编程方式设置输入时不会被调用。 See this for more info。基本上 OnChanges
钩子被触发 当输入仅通过视图传递时 .
这个问题的解决方案是让主机组件成为测试组件的父组件,并通过主机组件的模板传递输入。
这是完整的工作代码:
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();
})
});
您还可以选择手动调用 ngOnChanges
挂钩并在那里传递所需的更改对象。但是这并没有设置组件属性,只是调用了变化逻辑。
const previousValue = moment('2016-03-01T01:00:00Z');
const currentValue = moment('2016-02-28T01:00:00Z');
const changesObj: SimpleChanges = {
prop1: new SimpleChange(previousValue, currentValue),
};
component.ngOnChanges(changesObj);
请注意,此方法可以很好地测试 ngOnChanges
内部的逻辑,但它不会测试 @Input
装饰器是否已正确设置。
在Angular 4、测试时要手动触发ngOnChanges()
,需要手动调用(上面已经指出),只需要匹配new call signature of SimpleChange():
let prev_value = 'old';
let new_value = 'new';
let is_first_change: boolean = false;
component.ngOnChanges({
prop1: new SimpleChange(prev_value, new_value, is_first_change),
});