Dynamically load JSON for ngMock httpBackend response in Protractor

1.6k views Asked by At

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.

2

There are 2 answers

1
Delian Mitankin On BEST ANSWER

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);
0
helion3 On

Well, loading the json directly works.

// Allow JSON
$httpBackend.whenGET(/.*\.json$/).passThrough();

$http.get('/path/to/file.json').success(function(json) {
  // other httpBackend code here
});