Javascript 如何在AngularJS2中对组件进行单元测试;最后一句;?
我目前正试图为一个非常简单的AngularJs2组件编写一个单元测试 这是类型脚本:Javascript 如何在AngularJS2中对组件进行单元测试;最后一句;?,javascript,unit-testing,angular,typescript,components,Javascript,Unit Testing,Angular,Typescript,Components,我目前正试图为一个非常简单的AngularJs2组件编写一个单元测试 这是类型脚本: // cell.component.ts import { Component, Input } from '@angular/core'; import Cell from './cell'; @Component({ moduleId: module.id, selector: 'cell', templateUrl: 'cell.component.html', styl
// cell.component.ts
import { Component, Input } from '@angular/core';
import Cell from './cell';
@Component({
moduleId: module.id,
selector: 'cell',
templateUrl: 'cell.component.html',
styleUrls: ['cell.component.css']
})
export class CellComponent {
@Input()
cell = Cell;
}
这是模板:
<!-- cell.component.html -->
<div class="ticTacToe--board-cell ticTacToe--board-cell--{{cell.background}}">
<div class="ticTacToe--board-cell--{{cell.displayMarker()}}">{{cell.displayMarker()}}</div>
</div>
这在以下情况下失败:
Chrome 49.0.2623(Windows XP 0.0.0)CellComponent应渲染单元格
FAILED1][1]失败:未捕获(承诺中):错误:错误中
app/cell.component.html:1:9原因:self.context.cell.displayMarker
不是函数[1]错误:未捕获(承诺中):错误:错误
在app/cell.component.html中:1:9由以下原因引起:
self.context.cell.displayMarker不是函数
但是displayMarker是我的Cell类中的一个函数:
import Marker from './marker.enum';
export class Cell {
id: number;
private marker: Marker;
private background = 'background';
constructor(id: number) {
this.id = id;
}
displayMarker() {
return Marker[this.marker];
}
getMarker() {
return this.marker;
}
setMarker(marker: Marker) {
if (!this.marker) {
this.marker = marker;
}
}
declareWinner() {
this.background = 'winner';
}
isEmpty() {
return this.marker === undefined;
}
}
export default Cell;
。。。当手动测试(而不是通过业力/茉莉花)时,效果很好
有没有办法让我的单元测试工作起来?有几个错误
fixture.nativeElement
不提供被测组件,而是提供DOM元素。为什么你认为你可以做组件测试。querySelectorAll
您应该改为使用fixture.componentInstance
来获取测试中的组件谢谢你的反馈。将对此进行检查。尝试根据您的反馈更改我的CellComponent类,但不幸的是最终结果完全相同:-(也就是说,当我重新启动游戏时,我注意到transpiler正在抱怨在规范文件中使用async至少需要es2015…我不知道这是否是一个单独的问题…你是否修复了问题2?至于transpiler问题,我不确定,对不起,我在最后一次评论时还没有醒来。我重新阅读并查看了我的c。)又唱了一首颂歌,它现在起作用了。:-)干杯!
import Marker from './marker.enum';
export class Cell {
id: number;
private marker: Marker;
private background = 'background';
constructor(id: number) {
this.id = id;
}
displayMarker() {
return Marker[this.marker];
}
getMarker() {
return this.marker;
}
setMarker(marker: Marker) {
if (!this.marker) {
this.marker = marker;
}
}
declareWinner() {
this.background = 'winner';
}
isEmpty() {
return this.marker === undefined;
}
}
export default Cell;
export class CellComponent {
@Input()
cell = Cell; <===========
}
@Input() cell: Cell;
const fixture = TestBed.createComponent(CellComponent);
const componentUnderTest = fixture.nativeElement;