In AngularJS, mocking backend responses in tests can be achieved using tools like $httpBackend
or $httpBackend.whenGET()
to simulate HTTP requests and define the responses. This allows you to isolate the frontend code from the actual backend services, making your tests more reliable and independent of external dependencies.
Here's a step-by-step guide on how to mock backend responses in AngularJS tests using $httpBackend
:
Inject $httpBackend
: First, inject the $httpBackend
service into your test suite.
javascriptbeforeEach(inject(function($httpBackend) {
// Inject $httpBackend here
}));
Mock HTTP Responses: Use $httpBackend.whenGET()
to define the responses for specific HTTP requests.
javascriptbeforeEach(inject(function($httpBackend) {
$httpBackend.whenGET('/api/data')
.respond(200, { data: 'mocked response' });
}));
Flush Pending Requests: After setting up the responses, call $httpBackend.flush()
to flush any pending requests.
javascriptbeforeEach(inject(function($httpBackend) {
$httpBackend.whenGET('/api/data')
.respond(200, { data: 'mocked response' });
$httpBackend.flush();
}));
Perform Tests: Now, perform your tests as usual. AngularJS will use the mocked responses instead of making actual HTTP requests.
javascriptit('should fetch data from backend', inject(function($http, $httpBackend) {
var responseData;
$http.get('/api/data').then(function(response) {
responseData = response.data;
});
$httpBackend.flush();
expect(responseData).toEqual({ data: 'mocked response' });
}));
Verify Requests: Optionally, you can verify that the expected requests were made using $httpBackend.expectGET()
.
javascriptit('should make a GET request to /api/data', inject(function($http, $httpBackend) {
$http.get('/api/data');
$httpBackend.expectGET('/api/data');
$httpBackend.flush();
}));
Remember to clean up the mocked requests after each test to avoid any interference with subsequent tests:
javascriptafterEach(inject(function($httpBackend) {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
}));
By following these steps, you can effectively mock backend responses in your AngularJS tests, ensuring that your frontend code behaves as expected regardless of the actual backend services.