routeLink在测试时未正确呈现

时间:2017-03-14 21:37:39

标签: unit-testing angular routelink

我的标题组件定义如下:

import { Component, OnChanges, Input } from '@angular/core';
@Component({
  selector: 'app-section-header',
  template:`
  <div class="pageTitle">
    <h1>{{name}}</h1>
      <a class="editBtn" [routerLink]="routerLink">edit</a>
  </div>
  <div class="progress"></div>
  `,
  styleUrls: ['./section-header.component.css']
})
export class SectionHeaderComponent implements OnChanges  {
  public routerLink: string[];
  @Input() name: string;

  ngOnChanges() {
    this.routerLink = ['/section', this.name, 'edit'];
  }
}

此组件从其父组件获取绑定“名称”,稍后它用于构成routeLink的一部分以“编辑”屏幕。

运行应用程序时运行良好。

出于某种原因,我无法测试此链接的正确创建:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { SectionHeaderComponent } from './section-header.component';
import { RouterTestingModule } from '@angular/router/testing';
import { Component, Input, Injectable, OnChanges , SimpleChanges, Output,SimpleChange,  EventEmitter} from '@angular/core'
fdescribe('SectionHeaderComponent', () => {
  let component: SectionHeaderComponent;
  let fixture: ComponentFixture<SectionHeaderComponent>;
  let  element, de;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [SectionHeaderComponent]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SectionHeaderComponent);
    component = fixture.componentInstance;
    element = fixture.nativeElement;      // to access DOM element
    de = fixture.debugElement; 
  });

  it('should create link to edit view', () => {
    component.name='sasha';
    fixture.detectChanges();

    component.ngOnChanges();
    fixture.whenStable().then(() => { 
      expect(element.querySelector('h1').innerText).toBe('Sasha');
//for some reason this test failing with error expected '/'is not
// equal to 'section/sasha/edit' 
 expect(de.query(By.css('a')).nativeElement.getAttribute('href')).toBe  ('/section/sasha/edit');
    });
  });
});

我哪里出错了? 谢谢

1 个答案:

答案 0 :(得分:1)

在调用fixture.detectChanges()之后,您需要致电ngOnChanges() 。进行此更改后,它应该可以正常工作

Plunker

it('should create link to edit view', () => {
  component.name = 'sasha';
  component.ngOnChanges();
  fixture.detectChanges()
  expect(element.querySelector('h1').innerText).toBe('sasha');

  expect(de.query(By.css('a')).nativeElement.getAttribute('href'))
      .toBe('/section/sasha/edit');
});