Testing services

To check that your services are working as you intend, you can write tests specifically for them.

Angular TestBed

The TestBed is the most important of the Angular testing utilities. The TestBed creates a dynamically-constructed Angular test module that emulates an Angular @NgModule.

The TestBed.configureTestingModule() method takes a metadata object that can have most of the properties of an @NgModule.

To test a service, you set the providers metadata property with an array of the services that you'll test or mock.

let service: ValueService;

beforeEach(() => {
  TestBed.configureTestingModule({ providers: [ValueService] });
});

For example:

beforeEach(() => {
    console.log('Calling beforeEach');
    loggerSpy = jasmine.createSpyObj('LoggerService', ['log']); // Call the spy

    TestBed.configureTestingModule({
        providers: [
            CalculatorService,
            {
                provide: LoggerService,
                useValue: loggerSpy
            }
        ]
    });

    calculator = new CalculatorService(loggerSpy); // Call the calculator
});

Last updated