Search code examples
angularjsprotractorangularjs-e2ee2e-testingngmocke2e

How to setup e2e protractor backend request mocking/stubbing


I try to setup my independent protractor project to mock some of my backend requests. Therefore, I included angular-mocks.js and attached another module within the onPrepare() function of my protractor.conf.js:

browser.addMockModule('httpBackend', function() {
    angular.module('httpBackend', ['myApp', 'ngMockE2E']).run(function($httpBackend) {
        $httpBackend.whenPOST(/^requests\/*/).respond(function(method, url, data) {
            var obj = {"msg": "Response!"};
            return [200, JSON.stringify(obj), {}];
        });
    })
})    

This lets me intercept any request but I am not getting what I want to return in respond(). It seems I am just getting a 200 OK.

What am I doing wrong?


Solution

  • Just to let you know how I solved it:

    The docs say the following:

    The respond method takes a set of static data to be returned or a function that can return an array containing response status (number), response data (string), response headers (Object), and the text for the status (string).

    In my case, the headers Object somehow does not seem to be optional and I ended with setting it on my own before returning the array:

    browser.addMockModule('httpBackend', function() {
        angular.module('httpBackend', ['myApp', 'ngMockE2E']).run(function($httpBackend) {
            $httpBackend.whenPOST(/^requests\/*/).respond(function(method, url, data) {
                var obj = {"msg": "Response!"},
                    resHeader = {
                        "Cache-Control": "no-cache, no-store, max-age=0",
                        "Date": "Tue, 24 Nov 2015 17:08:57 GMT",
                        "Pragma": "no-cache",
                        "Transfer-Encoding": "chunked",
                        "Content-Type": "application/json; charset=UTF-8",
                        "Expires": "Thu, 01 Jan 1970 00:00:00 GMT",
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Allow-Headers": "origin,x-requested-with,access-control-request-headers,content-type,access-control-request-method,accept",
                        "Access-Control-Allow-Methods": "POST, GET, OPTIONS, DELETE",
                        "Access-Control-Credentials": "true",
                        "Content-Language": "de-DE",
                        "Access-Control-Max-Age": "3600"
                    };
                return [200, JSON.stringify(obj), resHeader];
            });
        })
    })
    

    Anybody has a clue why this is necessary or which of its attributes is obsolete?