首页 > 解决方案 > 使用@input 对角度组件进行单元测试

问题描述

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

标签: angularunit-testinginput

解决方案


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

组件的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

我假设所有这些都在 a 中beforeEach,如果您想要 s 的不同值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
   });
  });
});

推荐阅读