【问题标题】:Angular 5 jasmine tests, component not compilingAngular 5 jasmine 测试,组件未编译
【发布时间】:2018-10-02 19:46:12
【问题描述】:

我正在尝试编写一个简单的单元测试,但无法编译我的模板。 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>

【问题讨论】:

  • 如果你能带上组件的代码会更容易回答
  • 好的我已经添加了
  • 在每个 it() 中创建您的 fixture ( TestBed.createComponent() ) 和组件实例引用

标签: javascript angular jasmine


【解决方案1】:

您必须设置组件的“文本”公共属性-只有它才会在 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);
}));

【讨论】:

  • 啊好吧,这不是问题,但fixture.detectChanges 似乎解决了问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-08-01
  • 2017-11-06
  • 2018-10-25
  • 2017-09-15
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多