Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 带有输入绑定和路由器链接的单元测试角度组件给出错误';无法读取属性'__来源';未定义的';_Angular_Unit Testing_Jasmine - Fatal编程技术网

Angular 带有输入绑定和路由器链接的单元测试角度组件给出错误';无法读取属性'__来源';未定义的';

Angular 带有输入绑定和路由器链接的单元测试角度组件给出错误';无法读取属性'__来源';未定义的';,angular,unit-testing,jasmine,Angular,Unit Testing,Jasmine,我正在尝试为一个@Input属性的组件编写一个单元测试,该属性恰好包含一个带有[routerLink]的锚定标记 我得到了一个错误: 失败:模板分析错误:无法绑定到“routerLink”,因为它不是“a”的已知属性。 为了解决这个问题,我添加了RouterTestingModule,现在得到了这个错误: TypeError:无法读取未定义的属性“\uu source” 每次测试 组件。ts import {Component, Input, OnInit} from '@angular/cor

我正在尝试为一个@Input属性的组件编写一个单元测试,该属性恰好包含一个带有[routerLink]的锚定标记

我得到了一个错误:

失败:模板分析错误:无法绑定到“routerLink”,因为它不是“a”的已知属性。

为了解决这个问题,我添加了
RouterTestingModule
,现在得到了这个错误:

TypeError:无法读取未定义的属性“\uu source”

每次测试

组件。ts

import {Component, Input, OnInit} from '@angular/core';
import {Tile, TileDefinition} from "../../model/tile";
import {TilesService} from "../../services/tiles.service";
import {Observable} from "rxjs";

@Component({
  selector: 'app-tile',
  templateUrl: './tile.component.html',
  styleUrls: ['./tile.component.scss']
})
export class TileComponent implements OnInit {

  @Input() tile: Tile;

  percentComplete: string;

  detailsExposed: boolean = false;
  public tileDescription: Observable<TileDefinition>;


  constructor(private tileService: TilesService) { }

  ngOnInit() {
    let num = parseInt(this.tile.custom3);
    if(isNaN(num)){
      this.percentComplete = '0%';
    } else {
      this.percentComplete = parseInt(this.tile.custom3).toString() + '%';
    }
  }

  showDetails(): void {
    this.detailsExposed = true;
    this.tileDescription = this.tileService.getTileDefinition(this.tile.id);
  }

  hideDetails(): void {
    this.detailsExposed = false;
  }
}

从'@angular/core'导入{Component,Input,OnInit};
从“./../model/Tile”导入{Tile,TileDefinition};
从“../../services/tiles.service”导入{tileService}”;
从“rxjs”导入{observeable};
@组成部分({
选择器:“应用程序磁贴”,
templateUrl:'./tile.component.html',
样式URL:['./tile.component.scss']
})
导出类TileComponent实现OnInit{
@Input()平铺:平铺;
完成百分比:字符串;
detailsExposed:boolean=false;
公共瓷砖说明:可见;
构造函数(私有tileService:tileService){}
恩戈尼尼特(){
让num=parseInt(this.tile.custom3);
if(isNaN(num)){
此.percentComplete='0%';
}否则{
this.percentComplete=parseInt(this.tile.custom3.toString()+'%';
}
}
showDetails():void{
this.detailsExposition=true;
this.tileDescription=this.tileService.getTileDefinition(this.tile.id);
}
hideDetails():void{
this.detailsExposition=false;
}
}
Component.html

<div class="row no-gutters mx-1 py-2 border-bottom">
  <div class="col-1">{{ tile.id }}</div>
  <div class="col">{{ tile.name }}</div>
  <div class="col-2">
    <div class="form-row">
      <div class="col">
        <div class="progress">
          <div class="progress-bar"
               [ngClass]="{'bg-success': percentComplete == '100%'}"
               [ngStyle]="{'width': percentComplete}">
            {{percentComplete}}
          </div>
        </div>
      </div>

      <div class="col-auto">
        <button class="btn btn-xs btn-light border text-primary show_more_button" *ngIf="!detailsExposed" (click)="showDetails()">More
        </button>
        <button class="btn btn-xs btn-light border text-primary show_less_button" *ngIf="detailsExposed" (click)="hideDetails()">Less
        </button>
      </div>
    </div>
  </div>
</div>

<div class="p-3 mx-1 border rounded-bottom bg-white" *ngIf="detailsExposed">
  <ng-container *ngIf="tileDescription | async; else loading">

    <a [routerLink]="['/fileeditor','tile',tile.id,'json','definitions']" class="btn btn-sm btn-info">Edit Configuration</a>

  </ng-container>

  <ng-template #loading>
    <div class="col-12 text-center"><p class="display-4 text-muted">Loading</p></div>
  </ng-template>

</div>


{{tile.id}
{{tile.name}
{{percentComplete}}
更多
较少的
编辑配置

加载

测试规范

import {async, ComponentFixture, TestBed} from '@angular/core/testing';

import {TileComponent} from './tile.component';
import {TilesService} from "../../services/tiles.service";
import {Component, DebugElement, ViewChild} from "@angular/core";
import {Tile, TileDefinition} from "../../model/tile";
import {By} from "@angular/platform-browser";
import {RouterTestingModule} from "@angular/router/testing";
import {of} from "rxjs";

// mock a host container so we can input bind to the unit under test
@Component({
  template: '<app-tile [tile]="tile"></app-tile>'
})
class HostComponent{
  tile: Tile = {
    id: "5",
    name: "TileName",
    custom3: "20% imaged"
  };
  @ViewChild(TileComponent) tileComponent: TileComponent;
}

describe('TileComponent', () => {
  let component: HostComponent;
  let fixture: ComponentFixture<HostComponent>;
  let tilesServiceSpy: { getTileDefinition: jasmine.Spy }; // we'll use a spy in place of the real service

  beforeEach(async(() => {
    // create the spy to inject as a substitute for the real TileService
    const tilesService = jasmine.createSpyObj('TilesService', ['getTileDefinition']);

    TestBed.configureTestingModule({
      declarations: [ HostComponent, TileComponent ],
      providers: [{ provide: TilesService, useValue: tilesServiceSpy}],
      imports: [RouterTestingModule.withRoutes([])]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HostComponent);
    component = fixture.componentInstance;
    tilesServiceSpy = TestBed.get(tilesServiceSpy); // we want to get the 'real' instance from our env
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should set percentcomplete on init', () => {
    expect(component.tileComponent.percentComplete).toBeUndefined('starts undefined');
    fixture.detectChanges(); // ngOnInit
    expect(component.tileComponent.percentComplete).toEqual('60%', 'set percentCompete on init')
  });
});

从'@angular/core/testing'导入{async,ComponentFixture,TestBed};
从“./tile.component”导入{TileComponent};
从“../../services/tiles.service”导入{tileService}”;
从“@angular/core”导入{Component,DebugElement,ViewChild};
从“./../model/Tile”导入{Tile,TileDefinition};
从“@angular/platform browser”导入{By}”;
从“@angular/router/testing”导入{RouterTestingModule}”;
从“rxjs”导入{of};
//模拟一个主机容器,这样我们就可以输入绑定到被测试的单元
@组成部分({
模板:“”
})
类主机组件{
平铺:平铺={
id:“5”,
名称:“TileName”,
客户3:“20%已成像”
};
@ViewChild(TileComponent)TileComponent:TileComponent;
}
描述('TileComponent',()=>{
let组件:主机组件;
let夹具:组件夹具;
让TileServiceSpy:{getTileDefinition:jasmine.Spy};//我们将使用Spy来代替真正的服务
beforeach(异步(()=>{
//创建要注入的间谍以替代真正的TileService
const tileService=jasmine.createSpyObj('tileService',['getTileDefinition']);
TestBed.configureTestingModule({
声明:[主机组件,TileComponent],
提供程序:[{provide:TilesService,useValue:tilesServiceSpy}],
导入:[RouterTestingModule.withRoutes([])]
})
.compileComponents();
}));
在每个之前(()=>{
fixture=TestBed.createComponent(主机组件);
组件=fixture.componentInstance;
tilesServiceSpy=TestBed.get(tilesServiceSpy);//我们想从环境中获取“真实”实例
});
它('应该创建',()=>{
expect(component.toBeTruthy();
});
它('应在初始化时设置完成百分比',()=>{
expect(component.tileComponent.percentComplete).toBeUndefined('start undefined');
fixture.detectChanges();//ngOnInit
expect(component.tileComponent.percentComplete).toEqual('60%,'set percentcompetite on init')
});
});

在本例中,您的行用于
tileServiceSpy=TestBed.get(tileServiceSpy)需要改为
tilesServiceSpy=TestBed.get(TilesService)

在那次改变之后,你很可能能够继续