Angular 2 Testing in Depth: Services
Service
Service
import { Injectable } from '@angular/core';
@Injectable()
export class Engine {
getHorsepower() {
return 150;
}
getName() {
return 'Basic engine';
}
}
test file
V1)
import { Engine } from './engine.service';
describe('Engine', () => {
it('should return it\'s horsepower', () => {
let subject = new Engine();
expect(subject.getHorsepower()).toEqual(150);
});
});
V2)
describe('Engine', () => {
let subject: Engine;
beforeEach(() => {
subject = new Engine();
});
it('should return it\'s horsepower', () => {
expect(subject.getHorsepower()).toEqual(150);
});
it('should return it\'s horsepower', () => {
expect(subject.getName()).toEqual('Basic engine');
});
});
V3)
import { TestBed, inject } from '@angular/core/testing';
import { Engine } from './engine.service';
import { Car } from './car.service';
describe('Car', () => {
let subject: Car;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [Engine, Car]
});
});
beforeEach(inject([Car], (car: Car) => {
subject = car;
}));
it('should display name with engine', () => {
expect(subject.getName()).toEqual('Car with Basic engine(150 HP)');
});
});
or
it('should display name with engine', inject([Car], (car: Car) => {
expect(car.getName()).toEqual('Car with Basic engine(150 HP)');
}));
or
beforeEach(() => {
TestBed.configureTestingModule({
providers: [Engine, Car]
});
spyOn(Engine.prototype, 'getHorsepower').and.returnValue(400);
spyOn(Engine.prototype, 'getName').and.returnValue('V8 engine');
});
it('should display name with engine', () => {
expect(subject.getName()).toEqual('Car with V8 engine(400 HP)');
});
V4)
Mcok Service
@Injectable()
class V8Engine {
getHorsepower() {
return 400;
}
getName() {
return 'V8 engine';
}
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: Engine, useClass: V8Engine },
Car
]
});
});
References
https://dzone.com/articles/angular-2-testing-in-depth-services
https://developers.livechatinc.com/blog/angular-dependency-injection-components/
http://blog.danieleghidoli.it/2016/11/06/testing-angular-component-mock-services/
No comments:
Post a Comment