【发布时间】:2020-10-08 10:57:27
【问题描述】:
所以我目前正在为 Angular 9 组件编写 Jasmine/Karma 单元测试。
我的应用程序如何工作的简短摘要:
我用 D3 写了一点Funnel,它以类似漏斗的图表显示给定数据。然后我写了一个FunnelComponent,其中包含这个Funnel,并在实际图表旁边显示了一些元信息。
这是我要测试的组件:
funnel.component.ts
import { Component } from '@angular/core';
import { Funnel } from './d3charts/funnel.ts';
import { FunnelData } from './funnel.data';
@Component({
selector: 'v7-funnel-component',
templateUrl: './funnel.html'
})
export class FunnelComponent {
private funnel: Funnel = null;
constructor() {}
public createFunnel(funnelData: FunnelData): void {
this.funnel = new Funnel();
this.funnel.setData(funnelData);
this.funnel.draw();
}
}
这是我对该组件的 karma-jasmine 单元测试:
funnel.component.spec.ts
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { } from 'jasmine';
import { FunnelComponent } from './funnel.component';
import { Component } from '@angular/core';
import { FunnelData } from './funnel.data';
import { Funnel } from './d3charts/funnel.ts';
@Component({selector: 'funnel', template: ''})
class FunnelStub {
private data: FunnelData = null;
public setData(data: FunnelData): void
{this.data = data;}
{}
public draw(): void
{}
public update(funnelData: FunnelData): void
{}
}
/**
* Testing class for FunnelComponent.
*/
describe('Component: Funnel', () => {
let component: FunnelComponent;
let fixture: ComponentFixture<FunnelComponent>;
beforeEach(async(() => {
TestBed
.configureTestingModule({
declarations: [
FunnelComponent,
FunnelStub
],
providers: [
{ provide: Funnel, useValue: FunnelStub}
]
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(FunnelComponent);
component = fixture.componentInstance;
});
}));
it('#createFunnel should set data of funnel. Filled data should set filled funnel.', () => {
expect(component["funnel"]).toBeNull();
let exampleFunnelData = new FunnelData("testcaption", "testdescription", 8);
component.createFunnel(exampleFunnelData);
expect(component["funnel"]).toBeDefined();
expect(component["funnel"]["data"]).toBeDefined();
expect(component.data.caption).toEqual("testcaption");
expect(component.data.description).toEqual("testsubtext");
expect(component.data.value).toEqual(8);
});
});
我想在这里测试createFunnel 方法。
但我不希望我的 createFunnel 方法将真正的Funnel 分配给this.funnel,而是使用我的FunnelStub。
知道怎么做吗?
将{ provide: Funnel, useValue: FunnelStub} 添加到我的提供程序数组没有帮助:(
最好的问候, 塞巴斯蒂安
【问题讨论】:
标签: angular unit-testing karma-jasmine