【问题标题】:unit testing angular component with @input使用@input 对角度组件进行单元测试
【发布时间】:2020-09-11 00:23:52
【问题描述】:

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

【问题讨论】:

    标签: angular unit-testing input


    【解决方案1】:

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

    组件的ngOnInitTestBed.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 的不同值,你必须对 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
       });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 2019-05-15
      • 2020-07-10
      • 2019-10-26
      • 2021-12-01
      • 1970-01-01
      相关资源
      最近更新 更多