Chapter 7. Unit Testing Services and XHRs

In Chapters 5 and 6, we learned how to leverage existing AngularJS services, as well as create our very own AngularJS services. We created simple AngularJS services that we used to store state and communicate across different parts of the application, and services to allow for HTTP communication with our servers.

In Chapter 3, we saw how we might unit test our controllers. Now that we have started creating our own AngularJS services, we will look at how to unit test them. In particular, we will test controllers that use built-in AngularJS services, as well as our very own services. Finally, we will write unit tests for services and controllers that make HTTP requests, and see how we can mock out and leverage the AngularJS Dependency Injection.

Dependency Injection in Our Unit Tests

In Chapter 3, we saw how to leverage AngularJS Dependency Injection in our unit tests to test controllers. We asked for the $controller service, and then created controller instances as and when we needed them. $controller is actually an AngularJS service that we ask for in the unit test.

Similary, we can ask for any service that AngularJS knows about in our unit test, whether it comes from core AngularJS or is one of our own creations. AngularJS will figure out how to create it, what its dependencies are, and give us a fully instantiated service for testing.

Note

Don’t forget that to run these tests, you need to:

  1. Switch to the chapter7 folder.
  2. Run npm install karma ...

Get AngularJS: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.