javascript - Angular 5 Jasmine 测试,组件未编译

标签 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>

最佳答案

你必须设置component-only的“text”公共(public)属性,然后它才会在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);
}));

关于javascript - Angular 5 Jasmine 测试,组件未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49969640/

相关文章:

javascript - 为什么在ECMAScript 6中,U + D800和U + DBFF之间的代码点会生成一个一字串的字符串?

javascript - 如何用 jasmine-jquery 测试这个函数?

javascript - Protractor Jasmine 描述嵌套在 it block 中的 block

javascript - 为什么我的 Sass 在使用 Gulp 时没有出现?

javascript - Ajax/iFrame/FileSystemObject 上传

javascript - 从 JavaScript 模型中的现有属性返回未定义

angular - 无法匹配任何路线。 URL段: '' : When trying to use child routes and Ng2

javascript - 如何使用 RxJs 流式传输 HostListener 事件?

angularjs - Click() 函数在 Protractor 脚本中不起作用

javascript - 在 JavaScript 中将对象传递到数组中