使用@input

问题描述 投票:0回答:1

我有一个角度组件,它有一个@input属性并在

ngOnInit
上处理它。 通常,当对 @input 进行单元测试时,我只是将其指定为
component.inputproperty=value
,但在这种情况下我不能,因为它被用在
ngOnInit
上。 如何在
.spec.ts
文件中提供此输入值。 我能想到的唯一选择是创建一个测试主机组件,但如果有更简单的方法,我真的不想走这条路。

angular unit-testing input
1个回答
17
投票

做测试主机组件是一种方法,但我知道这可能需要太多工作。

组件的

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
发挥创意。

例如:

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
   });
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.