When creating Angular Components, by default a spec.ts file is created. By definition, a unit test should not call any files, databases, or services. We use a mock, or a stand in for services.
Mocking Services
To mock services, the jasmine.createSpyObj is used. Example:
loggingService = jasmine.createSpyObj('LoggingService', ['Info','Error']);
Providing Mocked Services
To use the mocked service, it is provied. Example:
TestBed.configureTestingModule({
providers: [
ErrorHandlerService,
{ provide: LoggingService, useValue: loggingService },
{ provide: HttpTestingController, useValue: httpTestingController }
],
});
Full Example
We have an error handler service and we want to ensure that the message is logged by using the Error method.
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorHandlerService } from './error-handler.service';
import { LoggingService } from './logging.service';
import { HttpTestingController } from '@angular/common/http/testing';
describe('ErrorHandlerService', () => {
let errorHandlerService: ErrorHandlerService;
let loggingService: LoggingService;
let httpTestingController: HttpTestingController;
beforeEach(() => {
loggingService = jasmine.createSpyObj('LoggingService', ['Info','Error']);
TestBed.configureTestingModule({
providers: [
ErrorHandlerService,
{ provide: LoggingService, useValue: loggingService },
{ provide: HttpTestingController, useValue: httpTestingController }
],
});
errorHandlerService = TestBed.inject(ErrorHandlerService);
httpTestingController = TestBed.inject(HttpTestingController);
});
it('should be created', () => {
expect(errorHandlerService).toBeTruthy();
});
it('should handle an error and log it', () => {
spyOn(console, 'error');
const error = new Error('Test error message');
errorHandlerService.handleError(error);
expect(console.error).toHaveBeenCalledWith(error);
expect(loggingService.Error).toHaveBeenCalledWith(error.message, [error]);
});
});
No comments:
Post a Comment