Angular2+ Unit Test a Service with a built in Serverservice











up vote
0
down vote

favorite












I'm trying to write Unit tests for the first time. Up to now I was able to write tests for "normal"/intern services. Now I'm stuck with a more complex Service:



@Injectable()
export class BaseToolsService {

vehicles: Array<Vehicle>;
tools: BehaviorSubject<Array<Tool>> = new BehaviorSubject<Array<Tool>>(undefined);
noBaseTools: BehaviorSubject<Array<Tool>> = new BehaviorSubject<Array<Tool>>(undefined);
vehiclesWithBaseTools: BehaviorSubject<Array<VehicleBaseToolsModel>> = new BehaviorSubject<Array<VehicleBaseToolsModel>>(undefined);

constructor(private readonly toolService: ToolService,
private readonly vehicleService: VehicleService,
private readonly notificationService: NotificationService) {
forkJoin([this.toolService.getTools('Asset,ToolType'),
this.vehicleService.getVehicles('Asset,VehicleModel')]).subscribe(results => {
this.tools.next(results[0]);
this.vehicles = results[1];
this.filterToolsAndConvertVehicles();
});
}

...


My setup of the Unit test so far is:



import {BaseToolsService} from './base-tools.service';
import {ToolService} from '../../../../core/services/api/tool.service';
import {VehicleService} from '../../../../core/services/api/vehicle.service';
import {NotificationService} from '../../../../core/services/intern/notification/notification.service';
import {async, getTestBed, TestBed} from '@angular/core/testing';

describe('Service: BaseToolsService', () => {

let service: BaseToolsService;

beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
ToolService,
VehicleService,
NotificationService,
BaseToolsService
]
});
const testBed = getTestBed();
service = testBed.get(BaseToolsService);
}));

...
// Some Tests


The Problem is that the Services ToolService and VehicleService try to get a server respond. Since they are built in the BaseToolsService I don't know how to mock the server request/backend or how to mock the required data itself and prevent the services to reach out for the server. When I run the test it of course fails with the error Failed: Http failure response for (unknown url): 0 Unknown Error.



Is there a way I can mock the server respond which is one level deeper than the service is i want to test? Or is the Problem somewhere else? (Since I'm new to Unit Tests I doubt I did everything correct)










share|improve this question


















  • 2




    Just mock BaseToolsService's collaborators, replace them with ones that don't make requests. When you're testing the services that do make requests directly, mock out the http client per the documenation: angular.io/guide/http#testing-http-requests. There's also general testing guidance: angular.io/guide/testing
    – jonrsharpe
    Nov 21 at 13:25












  • Or, alternatively, don't mock the whole service but spy the methods and return an of(data) instead of whatever the service would return. Check out jasmine spy of this.
    – Arne
    Nov 21 at 13:51










  • Thanks for the help @jonrsharpe, it just felt wrong to me to overwrite classes. But I guess that's the way to go.
    – Adrian
    Nov 30 at 8:33















up vote
0
down vote

favorite












I'm trying to write Unit tests for the first time. Up to now I was able to write tests for "normal"/intern services. Now I'm stuck with a more complex Service:



@Injectable()
export class BaseToolsService {

vehicles: Array<Vehicle>;
tools: BehaviorSubject<Array<Tool>> = new BehaviorSubject<Array<Tool>>(undefined);
noBaseTools: BehaviorSubject<Array<Tool>> = new BehaviorSubject<Array<Tool>>(undefined);
vehiclesWithBaseTools: BehaviorSubject<Array<VehicleBaseToolsModel>> = new BehaviorSubject<Array<VehicleBaseToolsModel>>(undefined);

constructor(private readonly toolService: ToolService,
private readonly vehicleService: VehicleService,
private readonly notificationService: NotificationService) {
forkJoin([this.toolService.getTools('Asset,ToolType'),
this.vehicleService.getVehicles('Asset,VehicleModel')]).subscribe(results => {
this.tools.next(results[0]);
this.vehicles = results[1];
this.filterToolsAndConvertVehicles();
});
}

...


My setup of the Unit test so far is:



import {BaseToolsService} from './base-tools.service';
import {ToolService} from '../../../../core/services/api/tool.service';
import {VehicleService} from '../../../../core/services/api/vehicle.service';
import {NotificationService} from '../../../../core/services/intern/notification/notification.service';
import {async, getTestBed, TestBed} from '@angular/core/testing';

describe('Service: BaseToolsService', () => {

let service: BaseToolsService;

beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
ToolService,
VehicleService,
NotificationService,
BaseToolsService
]
});
const testBed = getTestBed();
service = testBed.get(BaseToolsService);
}));

...
// Some Tests


The Problem is that the Services ToolService and VehicleService try to get a server respond. Since they are built in the BaseToolsService I don't know how to mock the server request/backend or how to mock the required data itself and prevent the services to reach out for the server. When I run the test it of course fails with the error Failed: Http failure response for (unknown url): 0 Unknown Error.



Is there a way I can mock the server respond which is one level deeper than the service is i want to test? Or is the Problem somewhere else? (Since I'm new to Unit Tests I doubt I did everything correct)










share|improve this question


















  • 2




    Just mock BaseToolsService's collaborators, replace them with ones that don't make requests. When you're testing the services that do make requests directly, mock out the http client per the documenation: angular.io/guide/http#testing-http-requests. There's also general testing guidance: angular.io/guide/testing
    – jonrsharpe
    Nov 21 at 13:25












  • Or, alternatively, don't mock the whole service but spy the methods and return an of(data) instead of whatever the service would return. Check out jasmine spy of this.
    – Arne
    Nov 21 at 13:51










  • Thanks for the help @jonrsharpe, it just felt wrong to me to overwrite classes. But I guess that's the way to go.
    – Adrian
    Nov 30 at 8:33













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'm trying to write Unit tests for the first time. Up to now I was able to write tests for "normal"/intern services. Now I'm stuck with a more complex Service:



@Injectable()
export class BaseToolsService {

vehicles: Array<Vehicle>;
tools: BehaviorSubject<Array<Tool>> = new BehaviorSubject<Array<Tool>>(undefined);
noBaseTools: BehaviorSubject<Array<Tool>> = new BehaviorSubject<Array<Tool>>(undefined);
vehiclesWithBaseTools: BehaviorSubject<Array<VehicleBaseToolsModel>> = new BehaviorSubject<Array<VehicleBaseToolsModel>>(undefined);

constructor(private readonly toolService: ToolService,
private readonly vehicleService: VehicleService,
private readonly notificationService: NotificationService) {
forkJoin([this.toolService.getTools('Asset,ToolType'),
this.vehicleService.getVehicles('Asset,VehicleModel')]).subscribe(results => {
this.tools.next(results[0]);
this.vehicles = results[1];
this.filterToolsAndConvertVehicles();
});
}

...


My setup of the Unit test so far is:



import {BaseToolsService} from './base-tools.service';
import {ToolService} from '../../../../core/services/api/tool.service';
import {VehicleService} from '../../../../core/services/api/vehicle.service';
import {NotificationService} from '../../../../core/services/intern/notification/notification.service';
import {async, getTestBed, TestBed} from '@angular/core/testing';

describe('Service: BaseToolsService', () => {

let service: BaseToolsService;

beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
ToolService,
VehicleService,
NotificationService,
BaseToolsService
]
});
const testBed = getTestBed();
service = testBed.get(BaseToolsService);
}));

...
// Some Tests


The Problem is that the Services ToolService and VehicleService try to get a server respond. Since they are built in the BaseToolsService I don't know how to mock the server request/backend or how to mock the required data itself and prevent the services to reach out for the server. When I run the test it of course fails with the error Failed: Http failure response for (unknown url): 0 Unknown Error.



Is there a way I can mock the server respond which is one level deeper than the service is i want to test? Or is the Problem somewhere else? (Since I'm new to Unit Tests I doubt I did everything correct)










share|improve this question













I'm trying to write Unit tests for the first time. Up to now I was able to write tests for "normal"/intern services. Now I'm stuck with a more complex Service:



@Injectable()
export class BaseToolsService {

vehicles: Array<Vehicle>;
tools: BehaviorSubject<Array<Tool>> = new BehaviorSubject<Array<Tool>>(undefined);
noBaseTools: BehaviorSubject<Array<Tool>> = new BehaviorSubject<Array<Tool>>(undefined);
vehiclesWithBaseTools: BehaviorSubject<Array<VehicleBaseToolsModel>> = new BehaviorSubject<Array<VehicleBaseToolsModel>>(undefined);

constructor(private readonly toolService: ToolService,
private readonly vehicleService: VehicleService,
private readonly notificationService: NotificationService) {
forkJoin([this.toolService.getTools('Asset,ToolType'),
this.vehicleService.getVehicles('Asset,VehicleModel')]).subscribe(results => {
this.tools.next(results[0]);
this.vehicles = results[1];
this.filterToolsAndConvertVehicles();
});
}

...


My setup of the Unit test so far is:



import {BaseToolsService} from './base-tools.service';
import {ToolService} from '../../../../core/services/api/tool.service';
import {VehicleService} from '../../../../core/services/api/vehicle.service';
import {NotificationService} from '../../../../core/services/intern/notification/notification.service';
import {async, getTestBed, TestBed} from '@angular/core/testing';

describe('Service: BaseToolsService', () => {

let service: BaseToolsService;

beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
ToolService,
VehicleService,
NotificationService,
BaseToolsService
]
});
const testBed = getTestBed();
service = testBed.get(BaseToolsService);
}));

...
// Some Tests


The Problem is that the Services ToolService and VehicleService try to get a server respond. Since they are built in the BaseToolsService I don't know how to mock the server request/backend or how to mock the required data itself and prevent the services to reach out for the server. When I run the test it of course fails with the error Failed: Http failure response for (unknown url): 0 Unknown Error.



Is there a way I can mock the server respond which is one level deeper than the service is i want to test? Or is the Problem somewhere else? (Since I'm new to Unit Tests I doubt I did everything correct)







angular unit-testing service server






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 at 13:22









Adrian

13




13








  • 2




    Just mock BaseToolsService's collaborators, replace them with ones that don't make requests. When you're testing the services that do make requests directly, mock out the http client per the documenation: angular.io/guide/http#testing-http-requests. There's also general testing guidance: angular.io/guide/testing
    – jonrsharpe
    Nov 21 at 13:25












  • Or, alternatively, don't mock the whole service but spy the methods and return an of(data) instead of whatever the service would return. Check out jasmine spy of this.
    – Arne
    Nov 21 at 13:51










  • Thanks for the help @jonrsharpe, it just felt wrong to me to overwrite classes. But I guess that's the way to go.
    – Adrian
    Nov 30 at 8:33














  • 2




    Just mock BaseToolsService's collaborators, replace them with ones that don't make requests. When you're testing the services that do make requests directly, mock out the http client per the documenation: angular.io/guide/http#testing-http-requests. There's also general testing guidance: angular.io/guide/testing
    – jonrsharpe
    Nov 21 at 13:25












  • Or, alternatively, don't mock the whole service but spy the methods and return an of(data) instead of whatever the service would return. Check out jasmine spy of this.
    – Arne
    Nov 21 at 13:51










  • Thanks for the help @jonrsharpe, it just felt wrong to me to overwrite classes. But I guess that's the way to go.
    – Adrian
    Nov 30 at 8:33








2




2




Just mock BaseToolsService's collaborators, replace them with ones that don't make requests. When you're testing the services that do make requests directly, mock out the http client per the documenation: angular.io/guide/http#testing-http-requests. There's also general testing guidance: angular.io/guide/testing
– jonrsharpe
Nov 21 at 13:25






Just mock BaseToolsService's collaborators, replace them with ones that don't make requests. When you're testing the services that do make requests directly, mock out the http client per the documenation: angular.io/guide/http#testing-http-requests. There's also general testing guidance: angular.io/guide/testing
– jonrsharpe
Nov 21 at 13:25














Or, alternatively, don't mock the whole service but spy the methods and return an of(data) instead of whatever the service would return. Check out jasmine spy of this.
– Arne
Nov 21 at 13:51




Or, alternatively, don't mock the whole service but spy the methods and return an of(data) instead of whatever the service would return. Check out jasmine spy of this.
– Arne
Nov 21 at 13:51












Thanks for the help @jonrsharpe, it just felt wrong to me to overwrite classes. But I guess that's the way to go.
– Adrian
Nov 30 at 8:33




Thanks for the help @jonrsharpe, it just felt wrong to me to overwrite classes. But I guess that's the way to go.
– Adrian
Nov 30 at 8:33

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53413000%2fangular2-unit-test-a-service-with-a-built-in-serverservice%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53413000%2fangular2-unit-test-a-service-with-a-built-in-serverservice%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Berounka

Sphinx de Gizeh

Different font size/position of beamer's navigation symbols template's content depending on regular/plain...