Angular 2 Service Unit Test With Http Mock in Javascript

In this example, we will create a jasmine unit test for an Angular2 service that uses Http. One of the key things in unit testing is mocking, so we will also see how we can mock Http in the unit test.

 

Below is the service that we are going to create unit test for. In case you didn’t know, this service was actually part of my previous post Angular 2 Service Example. The service method getCountriesByRegion simply retrieves data from http remote and transform response into json object.

Let’s start creating the unit test.

module? inject?

If you are familiar with Angular 1 unit test, you probably know that we can use ngMock  module to provide mocking for our tests. Below is what we usually do in Angular 1 tests.

We use module()  function to load our app module and use inject()  function to inject dependencies.

What’s in Angular 2

In Angular 2 world, the testing utilities are in ng.testing and there is no such “module” thing like Angular 1. We can just add provider and then inject dependencies where we need them, like below.

Or

Back to our example, since the app.CountryService requires Http, we want to mock the Http in unit test. Below is how we do it. So the Http injected into the service will be using MockBackend.

Ok, so we have everything we need now, the test object and a mocked Http. Next, we need to setup behavior for the mocked http backend – MockBackend, and it is done like below.

The above code basically tells the MockBackend to return a mock response with the responseObject in body.

Finally, we can test the service method getCountriesByRegion now.

If we put everything together, below is the full code of the jasmine test.

 

BTW, ng.testing exists in angular2-all-testing.umd.dev.js, so make sure you includ it in your path.

Resource


facebooktwittergoogle_plusredditlinkedin

Wayne Hong

Passionate Java full stack developer.