Search code examples
angularjsprotractorangularjs-ngmockngmocke2e

Dynamically load JSON for ngMock httpBackend response in Protractor


I'm building an ngMock httpBackend in a Protractor test.

var mockJson = require(projectRoot + 'mock/load.json');

var mockResource = function() {
    angular.module('aMockObject', ['myApp', 'ngMockE2E'])
    .run(function($httpBackend) {
        $httpBackend.whenGET('a/path').respond(mockJson);
    });
};

The default JSON object for the mock response needs to be loaded from a file.

However, the $httpBackend code is actually executed in the browser context, not the Protractor script context, so the mockJson variable is undefined.

Is there any other way to make this work? All I could think of is some sort of injected script tag to load the json file in the browser context.


Solution

  • You can pass data between protractor and your application with addMockModule:

    file.json

    {
        some_property: 'value'
    }
    

    aMockObject.js:

    exports.module = function (data) {
        angular.module('aMockObject', ['myApp', 'ngMockE2E'])
        .run(function($httpBackend) {
            $httpBackend.whenGET('a/path').respond(data);
        });
    };
    

    The init function:

    var aMockObject = require('aMockObject');    
    var file = require('file.json');    
    browser.addMockModule('aMockObject', aMockObject.module, file);