The aim of this article is to show you, how I mock my API when I test my angularjs applications.
First you will need to add angular-mock script to your application.
# Installation (via bower)bower install angular-mocks# And include this script in your angularjs app<script type="text/javascript" src="bower_components/angular-mocks/angular-mocks.js"></script>
You can now start to mock you http request.
You can mock backend with protractor using the browser.addMockModule()
method.
A test example :
describe('A test', function() {it('should diplay raoul in result' ,function() {browser.addMockModule('httpBackendMock',function() {angular.module('httpBackendMock',['mainApp', 'ngMockE2E']).run(function($httpBackend) {$httpBackend.whenGET('/results').respond('raoul');});});browser.get('/');var result = element(by.binding('result'));expect(result.getText()).toEqual('raoul');});})
Inconveniences:
I developped a tiny nodejs module to make your http mock easier : HttpBackend.
So now install the httpbackend module npm install httpbackend
And then test :
var HttpBackend = require('httpbackend');var backend;describe('Test Http backend methods', function() {beforeEach(function() {backend = new HttpBackend(browser);});afterEach(function() {backend.clear();});it('Test whenGET with string response', function() {backend.whenGET(/result/).respond('raoul');browser.get('/');var result = element(by.binding('result'));expect(result.getText()).toEqual('raoul');});});
Avantages: