我有一个 Angular 组件,它有一个@input 属性并在 ngOnInit
上处理它。通常,当对 @input 进行单元测试时,我只是将其指定为 component.inputproperty=value
但在这种情况下我不能,因为它被用于 ngOnInit
。我如何在 .spec.ts
文件中提供此输入值。我能想到的唯一选择是创建一个测试主机组件,但如果有更简单的方法,我真的不想走这条路。
最佳答案
做一个测试主机组件是一种方法,但我知道它可能工作量太大。
组件的 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
设置不同的值,您必须通过 describe
获得创意s 和 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
});
});
});
https://stackoverflow.com/questions/63839249/