我有一个具有@input属性的角度分量,并在ngOnInit
上进行处理。通常,在对@input进行单元测试时,我只是将其指定为component.inputproperty=value
,但在这种情况下,由于在ngOnInit
上使用了它,因此我不能这样做。如何在.spec.ts
文件中提供此输入值。我唯一能想到的选择就是创建一个测试主机组件,但是如果有更简单的方法,我真的不想走这条路。
答案 0 :(得分:1)
做一个测试主机组件是一种方法,但是我知道这可能是太多的工作。
在ngOnInit
之后的第一个fixture.detectChanges()
上调用组件的TestBed.createComponent(...)
。
因此,要确保将其填充在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
使用不同的值,则必须具有describe
和beforeEach
的创意。 / p>
例如:
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
});
});
});