So I'm currently writing a Jasmine/Karma Unit Test for an Angular 9 Component.
A short summary how my application works:
I've written a little Funnel
with D3 that displays given data in a funnel-like diagram. Then I've written a FunnelComponent
that contains this Funnel
and also displays some meta information next to the actual diagram.
This is my to be tested Component:
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();
}
}
And here is my karma-jasmine unit-test for that Component:
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);
});
});
I want to test the createFunnel
method here.
But I don't want that my createFunnel method assigns a real Funnel
to this.funnel
, but uses my FunnelStub
instead.
Any idea how to do this?
Adding { provide: Funnel, useValue: FunnelStub}
to my providers array didn't help :(
Best regards, Sebastian