Angular2单元测试

时间:2019-07-04 11:32:24

标签: angular karma-jasmine

我需要测试角度的技巧。我有应该测试的组件,现在需要帮助来做。

export class RadioButtonComponent implements AfterViewInit, OnDestroy {

  @Input('group')
  private _group: RadioGroupComponent;

  @ViewChild('radio', {static: true})
  private _matRadioButton: MatRadioButton;

  @Input('item')
  public item: any;

  public setSelected() {
    this._matRadioButton.checked = true;
  }

  ngAfterViewInit(): void {
    this._matRadioButton.radioGroup = this._group.getMatRadioGroup();
    this._group.addRadioButton(this);
  }

  ngOnDestroy(): void {
    this._matRadioButton.radioGroup = null;
    this._group.removeRadioButton(this);
  }
}

我该如何测试:

import { SharedModule } from './../../../app/shared/shared.module';
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { RadioButtonComponent } from 'src/core';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { RadioGroupComponent } from './radiogroup.component';



describe('RadioButtonComponent', () => {
   let fixture: ComponentFixture<RadioButtonComponent>;
   let component: RadioButtonComponent;
   beforeEach( async(() => {
     TestBed.configureTestingModule({
       imports:[SharedModule],
       schemas: [NO_ERRORS_SCHEMA]
     });

     fixture = TestBed.createComponent(RadioButtonComponent);
     component = fixture.debugElement.componentInstance;
     component['_group'] = new RadioGroupComponent();
     component['_group'].writeValue('test');
     component.ngAfterViewInit();
     fixture.detectChanges();


   }));

   describe('setSelected()', () => {
      it('should be selected', () => {

          const result = component.setSelected();

          expect(result).toBeTruthy();
     });
   });
});

基本上我的错误是:

  

失败:无法读取未定义的属性“值”

我需要帮助找出如何正确管理单元测试,以便测试可以通过。 您对我如何成功进行测试有任何建议吗?

亲切的问候, 丹尼尔(Danijel)

2 个答案:

答案 0 :(得分:0)

您的帖子中缺少一些细节,但是...

尝试删除多余的describe方法,其次,您不会在setSelected()方法中返回任何内容,因此它始终为false,请尝试通过单选检查单选按钮组件变量是否被选中(帮助) fakeAsync):

runtime: nodejs10.x

更新: 将_matRadioButton更改为public或重构您的setSelected方法,以便将操作读取为类似以下内容:

it('should be selected', fakeAsync() => {

  let status = component._matRadioButton.checked

  expect(status).toBeFalsy();

  component.setSelected();

  tick(15);

  expect(status).toBeTruthy();

});

答案 1 :(得分:0)

我找到了方法。首先必须实例化RadioButtonGroupComponent

const radioButtonGroupComponent: RadioButtonGroupComponent = new RadioButtonGroupComponent();

稍后由ComponentFixture创建RadioButtonComponent之后,我已经分配了实例。

fixture = TestBed.createComponent(RadioButtonComponent);
component = fixture.debugElement.componentInstance;
component['_group'] =  radioButtonGroupComponent

最后成功运行测试代码是:

 it('sholud be selected', () => {
    component.setSelected();
    const status = component['_matRadioButton'].checked;
    expect(status).toBeTruthy();
  });