Similar to this question on typemoq
injection, how can I inject ts-mockito objects into angular's TestBed.configureTestingModule()
? Any example ts-mockito tests I can find are independent of angular.
Consider the following minmal working example to test- it contains a ProgressComponent
, with a ProgressService
on the backend that we're mocking. The service is quite trivial:
import { Injectable } from '@angular/core';
@Injectable()
export class ProgressService {
private currentState: string = '1';
constructor() {
}
setCurrentState(state: string) {
this.currentState = state;
}
getCurrentState(){
return this.currentState
}
}
To mock this without ts-mockito
, we simply extend the class.
import {ProgressService} from "../../../progress.service";
export class MockProgressService extends ProgressService{}
And then when testing ProgressComponent
, the MockProgressService
is passed to the TestBed.
import {async, ComponentFixture, getTestBed, TestBed} from '@angular/core/testing'
import { ProgressComponent } from './progress.component'
import {ProgressService} from "../progress.service"
import {MockProgressService} from "../shared/services/progress/progress.mock";
describe('ProgressComponent', () => {
let injector: TestBed
let mockService: ProgressService
let fixture: ComponentFixture<ProgressComponent>
let component: ProgressComponent
beforeEach(async() => {
TestBed.configureTestingModule({
declarations: [ ProgressComponent ],
providers: [{provide: ProgressService, useClass: MockProgressService}]
}).compileComponents()
injector = getTestBed()
fixture = TestBed.createComponent(ProgressComponent)
component = fixture.componentInstance
mockService = injector.get(ProgressService)
fixture.detectChanges();
});
});
The angular test framework introduces dependency injection through the TestBed
. How can we use mockito within angular's test setup? For example, how can the snippet injector.get(ProgressService)
be made compatible with ts-mockito mocks?