Unit Testing with AngularJS: Understanding the Mock Objects

Mocking is the process of creating objects that replace the key components in an application to allow effective unit testing. Imagine that you need to test a controller behavior that makes an Ajax request using the $http service. The behavior depends on a number other components and systems: the AngularJS module to which the controller belongs, the $http service, the server that processes the request, the database that contains the data that is being asked for, and so on. When the test fails, you won’t know whether the problem is caused by the controller behavior you are trying to test or because of an unrelated fault; perhaps the server has crashed or can’t connect to the database, for example.

The components that the target for testing depends on are replaced with mock objects, which implement the API of the components that are required but generate fake, predictable results. You alter the behavior of the mock objects to create different scenarios in which to test your code, which makes it easy to arrange a wide range of tests without having to endlessly reconfigure test servers, databases, networks, and so on.

The Test Objects and APIs

In this section I am going to list the mock objects and some additional features that AngularJS provides to make testing easier. I’ll then use these in the rest of the chapter so that I can explain how they are used to create focused and effective unit tests. The ngMocks module contains a set of mock objects that are used to replace AngularJS components, as summarized in Table 25-5.

Most of these mock objects are reasonably simple, but they provide a good foundation for creating unit tests, and in the sections that follow, I’ll show you how they can be used to test different kinds of AngularJS components.

The angular.mock object provides methods that load modules and allows dependencies to be resolved in unit tests. I have described the available methods in Table 25-6.

In addition to the ngMocks module, AngularJS provides some methods and services that are useful for unit testing, as described in Table 25-7.

Source: Freeman Adam (2014), Pro AngularJS (Expert’s Voice in Web Development), Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *