This provider shares its namespace with the modules loaded before. So now we create our
mockService and tell the provider that when any controller or service asks for ItemSer
vice, give it our value.
Spies allow us to hook into certain functions, and check whether they were called,
how many times they were called, what arguments they were called with, and so on.
With AngularJS, as long as we include the angular-mocks.js file as part of the Karma
configuration, AngularJS takes care of ensuring that when we use the $http service, it
doesn’t actually make server calls.
// File: chapter7/serverAppSpec.js
describe('MainCtrl Server Calls', function() {
beforeEach(module('serverApp'));
var ctrl, mockBackend;
beforeEach(inject(function($controller, $httpBackend) {
mockBackend = $httpBackend;
mockBackend.expectGET('/api/note')
.respond([{id: 1, label: 'Mock'}]);
ctrl = $controller('MainCtrl');
// At this point, a server request will have been made
}));
it('should load items from server', function() {// Initially, before the server responds,// the items should be empty
expect(ctrl.items).toEqual([]);
// Simulate a server response// $httpBackend.flush(3) flush three request
mockBackend.flush();
expect(ctrl.items).toEqual([{id: 1, label: 'Mock'}]);
});
afterEach(function() {// Ensure that all expects set on the $httpBackend// were actually called
mockBackend.verifyNoOutstandingExpectation();
// Ensure that all requests to the server// have actually responded (using flush())
mockBackend.verifyNoOutstandingRequest();
});
});