Reputation: 2587
I want to use Jasmine/Karma to test a mock service, without it knowing about the real service. The problem is that it wants me to add all the dependencies from the real service, like, HttpErrorHandler and MessageService.
This is the real service code below:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { httpOptions } from '../http-options';
import { HttpErrorHandler, HandleError } from '../http-error-handler.service';
//
@Injectable({ providedIn: 'root' })
export class AboutService {
private handleError: HandleError;
constructor(
private http: HttpClient,
httpErrorHandler: HttpErrorHandler
) {
this.handleError = httpErrorHandler.createHandleError('AboutService');
}
// Skills
////////
getSkills() {
const url = 'path';
return this.http.get<any>(url, httpOptions)
.pipe(
catchError(this.handleError('getSkills', []))
);
}
}
and me .spec file
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AboutComponent } from './about.component';
//
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';// Other imports
import { AboutService } from './about.service';
// import { HttpErrorHandler } from '../http-error-handler.service';
// import { MessageService } from '../message.service';
// import { MaterialModule } from "../material/material.module";
class MocksService extends AboutService{
// getSkills() {
// return [someRandomArray];
// }
}
describe('AboutComponent', () => {
let component: AboutComponent;
let fixture: ComponentFixture<AboutComponent>;
//
let httpTestingController: HttpTestingController;
let service: AboutService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AboutComponent ],
imports: [ HttpClientTestingModule, MaterialModule ],
providers: [
{ AboutService, useClass: MocksService },
// HttpErrorHandler,
// MessageService
]
})
.compileComponents();
//
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(AboutService);
}));
beforeEach(() => {
fixture = TestBed.createComponent(AboutComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should be created', () => {
const service: AboutService = TestBed.get(AboutService);
expect(service).toBeTruthy();
});
});
Upvotes: 0
Views: 123
Reputation: 12980
You can just inject it and create spy's to mock whatever it is you're trying to mock/test:
const aboutService = TestBed.inject(AboutService);
const spy = spyOn(aboutService, 'getSkills').and.returnValue(of({...});
...
expect(spy).toHaveBeenCalled();
Upvotes: 1