组合组件

时间:2017-06-20 06:45:51

标签: angular unit-testing typescript karma-jasmine

我已经为angular2编写了一个compo组件,并为它编写了单元测试代码。由于我是初学者,所以我无法测试创建的组件。所以请帮我解决这个问题。

import { Component, Input, Output, EventEmitter } from "@angular/core";
import { ComboInterface } from './ComboInterface';

@Component({
  moduleId: module.id,
  selector: 'combo-compo',
  template: `
      <select name="theme" class="form-control" [ngModel]="selectedObject" (ngModelChange)="onChangeObj($event)">
        <option [ngValue]="theme" *ngFor="let theme of dataObject" >{{theme.value}}</option>
      </select>
            `
})

export class ComboComponent {
  selectedObject: ComboInterface;
  @Input() dataObject: Array<ComboInterface>;
  @Output() onComboChange = new EventEmitter();

  onChangeObj(newObj: ComboInterface) {
    this.selectedObject = newObj;
    this.onComboChange.emit(this.selectedObject);
  }

}

我已经为它编写了单元测试代码,如下所示

describe('ComboComponent Unit Test', () => {
    let comp: ComboComponent;
    let fixture: ComponentFixture<ComboComponent>;
    let de: DebugElement;
    let el: HTMLElement;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [ComboComponent], // declare the test component
            imports: [ReactiveFormsModule, FormsModule]
        });
        fixture = TestBed.createComponent(ComboComponent);
        comp = fixture.componentInstance;

    });

    it('should create ComboComponent', () => expect(comp).toBeDefined());

    it('should create a ComboComponent with values', () => {
        comp.dataObject = [
            {
                'value': 'Victoria Cantrell test',
                'key': '0839',
            }, {
                'value': 'Pearl Crosby Test',
                'key': '8262'
            }, {
                'value': 'Colette Foley Test',
                'key': '8968'
            }
        ];
                comp.onChangeObj(comp.dataObject[0]);
    });

});

运行npm test代码运行正常但是如何测试创建的组件?

1 个答案:

答案 0 :(得分:1)

测试使用断言。您可以使用expect进行断言。

例如,您希望组件发出一个值,对吗?

所以oyu必须在其上加上间谍:为了让它变得简单,间谍就会监视你的功能,看看它是否被称为

示例测试是:

it('onChangeObj should emit an event', () => {
    comp.dataObject = [/* data */];
    let spy = spyOn(component.onComboChange, 'emit');
    comp.onChangeObj(/* anything you want, even null */);
    expect(spy).toHaveBeenCalled();
});

它只是测试的一部分。在expect()上查看IDE的自动完成功能,了解您可以使用它做什么,您将在此之后了解如何进行测试!