【发布时间】:2020-01-18 05:09:18
【问题描述】:
我目前正在尝试模拟 Angular 单元测试的输入属性。不幸的是,我无法再进一步并反复收到以下错误消息:
TypeError: 无法读取未定义的属性“数据”
我的 HTML 模板如下所示
<div class="container-fluid">
<div class="row">
<div class="col-12">
<plot [data]="graph.data" [layout]="graph.layout"></plot>
</div>
</div>
</div>
我的组件是这样的:
...
export class ChartComponent implements OnInit {
@Input() currentChart: Chart;
currentLocationData: any;
public graph = {
data: [
{
type: 'bar',
x: [1, 2, 3],
y: [10, 20, 30],
}
],
layout: {
title: 'A simple chart',
},
config: {
scrollZoom: true
}
};
...
}
我的单元测试现在看起来很基础,但仍然抛出上述错误:
describe('ChartComponent', () => {
let component: ChartComponent;
let fixture: ComponentFixture<ChartComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ChartComponent],
imports: [
// My imports
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ChartComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
我尝试了不同的方法来模拟数据属性和currentChart@Input。
实现这一点并修复单元测试的正确方法是什么?
【问题讨论】:
-
在
expect块之前的 spec 文件中执行console.log(component.graph)会得到什么?
标签: angular typescript unit-testing karma-jasmine angular-unit-test