When writing unit tests though, we don’t really want to be hitting the Google API each time. So we need a way to mock out the calls.
A Service to Test
Let’s say we have the following service method in our code.
Here, we’re passing in an address string and getting back a promise. We then either resolve or fulfil that promise based on the Geocoder result.
So how do we test this?
Mocking
Jasmine Spies can be used to mock function calls. But, since a constructor for a JS object is just another function, we can mock this out in much the same way.
We still need a stub object to use in our tests though, so we can create one with just the geocode method.
All we need to do now is return the mock object from the constructor call.
Since it’s useful to start with a fresh object for each test, we can connect these up in a beforeEach in our Jasmine tests.
Using the Mock
Let’s say we wanted to test how our code would handle a response from the Geocoder that had no results. Using our mock, this would look like:
On lines 4-6, we’re setting up how our mocked Geocoder instance will respond to our calls. In this case, we’ll return an empty array and the ZERO_RESULTS flag from Google.
On lines 12-15, we can then assert that these methods have been called with the expected values.
What if we wanted to return results? In that case, we’ll need some results to return, so let’s create them first.