Angular2单元测试组件

时间:2016-10-01 19:18:58

标签: unit-testing angular karma-mocha

我正在学习Angular 2.0.0版本中的新功能和更改。我遇到了在测试组件中获取HTML元素的文本内容的问题。

这是我要测试的组件

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

@Component({
  selector: 'note-card',
  template: `
    <div
      class="note-card row shadow-1"
      [ngStyle]="{'background-color': note.color}"
      (mouseenter)="toggleCheck()"
      (mouseleave)="toggleCheck()"
    >
      <div class="icon" *ngIf="showCheck" (click)="onChecked()">
        <i class="material-icons">check</i>
      </div>
      <div class="col-xs-12 title">
        {{ note.title }}
      </div>
      <div class="col-xs-12 value">
        {{ note.value }}
      </div>
    </div>
  `
})
export class NoteCard {
  @Input() note = {};
  @Output() checked = new EventEmitter();

  showCheck: boolean = false;

  toggleCheck() {
    this.showCheck = !this.showCheck;
  }

  onChecked() {
    this.checked.next(this.note);
  }
}

这是该组件的单元测试

import {
  inject,
  async,
  TestBed,
  ComponentFixture,
} from '@angular/core/testing';
import { By } from '@angular/platform-browser';

import { Component } from '@angular/core';
import { NoteCard } from './note-card';

@Component({
  selector: 'note-card-test',
  template: '<note-card [note]="note"></note-card>'
})
class TestComponent {
  note = {
    value: 'note',
    title: 'title',
    color: 'red',
    id: 1
  }
}

describe('Note card', () => {
  beforeEach(() => TestBed.configureTestingModule({
    declarations: [TestComponent, NoteCard]
  }));

  it('should have correct title', async(() => {
    let fixture = TestBed.createComponent(TestComponent);


    fixture.whenStable().then(() => {
      const title = <HTMLElement>fixture.debugElement.query(By.css('.title')).nativeElement;

      console.log(fixture.componentInstance.note.title); // returns 'title'
      console.log(title); // return html element with empty text content
      expect(title.textContent.trim()).toEqual('title'); // failed, title.textContent.trim() is equal to ''
    });
  }));
});

fixture.componentInstance.note.title返回'title' 但title.textContent为空

知道可能出了什么问题?

1 个答案:

答案 0 :(得分:0)

我发现我需要调用fixture.detectChanges()来获取组件模板的当前状态

it('should have correct title', async(() => {
let fixture = TestBed.createComponent(TestComponent);


fixture.whenStable().then(() => {
  const title = <HTMLElement>fixture.debugElement.query(By.css('.title')).nativeElement;

  fixture.detectChanges();

  console.log(fixture.componentInstance.note.title); // returns 'title'
  console.log(title); // return html element with empty text content
  expect(title.textContent.trim()).toEqual('title'); // failed, title.textContent.trim() is equal to ''
});

}));

相关问题