做一个测试主机组件是一种方法,但我知道这可能是太多的工作。
组件的ngOnInit 在TestBed.createComponent(...) 之后的第一个fixture.detectChanges() 上被调用。
所以要确保它填充在ngOnInit 中,请将其设置在第一个fixture.detectChanges() 之前。
例子:
fixture = TestBed.createComponent(BannerComponent);
component = fixture.componentInstance;
component.inputproperty = value; // set the value here
fixture.detectChanges(); // first fixture.detectChanges call after createComponent will call ngOnInit
我假设所有这些都在 beforeEach 中,如果你想要 inputproperty 的不同值,你必须对 describes 和 beforeEach 有创意。
例如:
describe('BannerComponent', () => {
let component: BannerComponent;
let fixture: ComponentFixture<BannerComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({declarations: [BannerComponent]}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(BannerComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeDefined();
});
describe('inputproperty is blahBlah', () => {
beforeEach(() => {
component.inputproperty = 'blahBlah';
fixture.detectChanges();
});
it('should do xyz if inputProperty is blahBlah', () => {
// test when inputproperty is blahBlah
});
});
describe('inputproperty is abc', () => {
beforeEach(() => {
component.inputproperty = 'abc';
fixture.detectChanges();
});
it('should do xyz if inputProperty is abc', () => {
// test when inputproperty is abc
});
});
});