繁体   English   中英

使用@input 单元测试角度组件

[英]unit testing angular component with @input

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

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

ngOnInit的组件被称为第一fixture.detectChanges()TestBed.createComponent(...)

所以为了确保它被填充在ngOnInit ,在第一个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不同值, 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
   });
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM