1

我的标题组件定义如下:

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');
    });
  });
});

我哪里错了?谢谢

4

1 回答 1

1

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

普朗克

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');
});
于 2017-03-15T02:27:34.210 回答