Mocking and Stubbing with protractor Mocking and Stubbing with protractor selenium selenium

Mocking and Stubbing with protractor


This blog post discusses advance usage scenarios for Protractor. In particular it covers the the little know addMockModule() method of the Protractor browser object. The method allows you to create angular modules in Protractor (i.e. mocks or stubs of your API module) and upload them to the browser to replace the real implementation within the context of a given spec or set of specs.


You do not have access to $httpBackend, controllers or services from within a protractor test so the idea is to create another angular module and include it in the browser during the test.

  beforeEach(function(){    var httpBackendMock = function() {      angular.module('httpBackendMock', ['ngMockE2E', 'myApp'])        .run(function($httpBackend) {          $httpBackend.whenPOST('/api/packages').respond(200, {} );        })    }    browser.addMockModule('httpBackendMock', httpBackendMock)  })

ngMockE2E allows you to create a fake backend implementation for your application. Here is a more in depth post on the topic http://product.moveline.com/testing-angular-apps-end-to-end-with-protractor.html


Although I've not tried it myself at this point, Angular provides a mock $httpBackend for E2E tests:

http://docs.angularjs.org/api/ngMockE2E/service/$httpBackend

So, taking from the above docs page, I suspect you can use something like the following before your tests

beforeEach(function() {  $httpBackend.whenGET('/remote-url').respond(edgeCaseData);});