The AngularJS framework has a strong stance on HTTP requests in unit testing - all requests should be mocked.
Performing real HTTP requests in unit tests is discouraged for two main reasons. Unit tests should be fast and isolated, and making a real request can slow down the test significantly by introducing asynchrony. Additionally, using real requests breaks the isolation as the test outcome relies on both the unit being tested and the backend service.
To address this issue, AngularJS introduced the ngMock
module, automatically loaded in unit tests via angular-mocks.js. This module eliminates the need for developers to perform asynchronous Jasmine unit tests with Angular.
On the other hand, integration tests differ from unit tests as they may involve testing multiple units, potentially including a backend server through real HTTP requests. In such cases, Karma and Jasmine are still used, but the tests may run slower and require asynchrony.
In E2E tests, the ngMockE2E
module comes into play. While included in angular-mocks.js alongside ngMock
, it's not loaded by default. This module provides mocks suitable for end-to-end testing, with features like the e2e $httpBackend mock.
ngMockE2E
offers an alternate implementation of $httpBackend
for this purpose, with variations in its API usage. It's recommended not to use methods like flush
and extend
, and instead utilize $rootScope.$digest()
for executing promises.
However, integrating ngMockE2E
may face challenges due to adjustments made to Angular services by ngMock
. To resolve this, a helper module for integration tests such as 'ngMockI9n' can be utilized.
For smoother testing practices, a recipe for whitelisting real HTTP requests can make the process easier, though explicit enumeration of real and mocked requests is considered best practice.
In summary, when conducting integration tests that involve real requests, it's advisable to leverage $httpBackend
from ngMockE2E
, albeit requiring additional steps to ensure compatibility with ngMock
. Avoid real requests in unit tests to maintain the speed and quality of the tests.