Ok, if you don’t know anything about Services this post is not for you JUST yet. Learn about em and come back here…if you wanna.

For those that made it past my first two lines and continued, we all know that services handle API calls and make real requests. Testing code that requires a service would normally need to receive or send data. You do not want to make real calls, you want to run this unit of code in isolation with no external dependencies. Unit tests normally run with CI (continuous Integration). It is just not feasible to make real API calls (with the chance of failing or taking long time for responses and potential failures). So the question that you want answered is, How to mock API service calls for unit tests?

I have recently come across this problem seeing that I am an official FrontEnd developer (this has happened basically 4 weeks ago still fresh) and one of my duties is to create unit tests for my work. I did some basic assertions which worked fine but there came a problem when it came to requiring a service to unit test my code.

Let’s provide some context. You have a service called EventsService right, this guy has a method/call called getUsers. Simple. Now in the component that you are working with you need to import the EventsService to use that getUsers call for your unit tests as well as import the component you are unit testing.

UsersComponent using the eventServices.

So you use this guy(above) that makes the getUsers() method that is provided from the eventService upon the component’s ngOnInit() as seen in the image (still above).

With the code above this will make the request and return an observable which you can see we are subscribing to and initialising. So let us get to our spec component.

Added some comments for each step, sorry i know that there is a bit going on in this post. I tell ya explaining context is quite a challenge.

So you have declared and imported what services you need, and from there use spyOn to return an observable and set the data you wish to return, after that you would trigger the ngOnInit() from your component. There you have it, you have successfully faked an API call to return data that is to your liking and forming it at your will

Ideally the flow with unit testing is to use the 3 A rule

Arrange

Act

Assert

in the example i’ve been going on about, you can see that the first step was to arrange that service to provide mock data, the act would be to trigger the ngOnInit() from my users component and then Assert to see if the expect results are true.

Of course i am a newbie at this and i’ve i’m completely wrong please feel free to comment and point me in the right direction. Of course there are many way to peel a banana.

the Above examples is using Karma + Jasmine and Angular framework.