【发布时间】:2017-02-03 04:03:43
【问题描述】:
我目前正在尝试为一个非常简单的 AngularJs2 组件编写单元测试。
这是打字稿:
// 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>
这是我目前的测试:
// cell.component.spec.ts
import { async, inject, TestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { ReflectiveInjector } from '@angular/core';
import { CellComponent } from './cell.component';
import Cell from './cell';
import Marker from './marker.enum';
//TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
describe('CellComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [CellComponent]
});
});
it ('should render a cell', async(() => {
TestBed.compileComponents().then(() => {
// Arrange
const fixture = TestBed.createComponent(CellComponent);
const componentUnderTest = fixture.nativeElement;
const testId = 1;
const testMarker = Marker.X;
const testCell = new Cell(1);
testCell['marker'] = testMarker;
// Act
componentUnderTest.cell = testCell;
// Assert
fixture.detectChanges();
expect(componentUnderTest.querySelectorAll('div.ticTacToe--board-cell').length).toBe(1);
expect(componentUnderTest.querySelectorAll('div.ticTacToe--board-cell--background').length).toBe(1);
expect(componentUnderTest.querySelectorAll('div.ticTacToe--board-cell--X').length).toBe(1);
expect(componentUnderTest.querySelectorAll('div.ticTacToe--board-cell--X')[0].innerText).toBe('X');
});
}));
});
这失败了:
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;
...当手动测试时(而不是通过 Karma/Jasmine),这工作正常。
有什么想法可以让我的单元测试工作吗?
【问题讨论】:
标签: javascript unit-testing angular typescript components