使用@input对角度分量进行单元测试

pan*_*aya 3 unit-testing input angular

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

Ali*_*F50 15

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

组件ngOnInit的 会在第一个fixture.detectChanges()after 时被调用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
Run Code Online (Sandbox Code Playgroud)

我假设所有这些都在 a 中,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
   });
  });
});
Run Code Online (Sandbox Code Playgroud)