Angular 5茉莉花测试,组件不编译

时间:2018-04-22 18:58:56

标签: javascript angular jasmine

我试图编写一个简单的单元测试,但无法编译我的模板。 AppComponent有一个名为text的变量,该变量呈现为h1标记。在测试html时,它总是以''的形式返回。有谁知道我在这里失踪了什么?

测试代码

import {TestBed, async, ComponentFixture} from '@angular/core/testing';
import {AppComponent} from './app.component';

describe('AppComponent', () => {

  let fixture: ComponentFixture<AppComponent>;
  let component: AppComponent;
  const mainTitle = 'Angular Unit Testing';

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
      });
  }));

  it(`should render ${mainTitle} to an H1 tag`, async(() => {
    const compiled = fixture.debugElement.nativeElement;
    console.log('here', compiled.querySelector('h1'));
    expect(compiled.querySelector('h1').textContent).toEqual(mainTitle);
  }));

});

组件代码

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent {
  text = 'Angular Unit Testing';
}

HTML

<h1>{{text}}</h1>

1 个答案:

答案 0 :(得分:2)

您必须设置仅限组件的“text”公共属性,然后它将在h1标签

中呈现
it(`should render ${mainTitle} to an H1 tag`, async(() => {
  const compiled = fixture.debugElement.nativeElement;
  component.text = 'Angular Unit Testing';
  fixture.detectChanges(); 
  expect(compiled.querySelector('h1').textContent).toEqual(mainTitle);
}));