Using variables in httpBackend mock function

217 views Asked by At

I want to be able to define a variable and then use said variable in the respond() method inside the module.run() function. I have this code inside my it():

    var testValue=randomValue(); // suffice to say, a random value generator
    var httpBackendMock = function() {
        angular.module('httpBackendMock', ['ngMockE2E', 'name.of.app'])
            .run(function($httpBackend) {
                $httpBackend.whenPOST(/.*\/api\/data/).respond(function(method, url, data, headers) {
                    return [200, '<?xml version="1.0" encoding="UTF-8" standalone="yes"?> \
                    <data>'+testValue+'</data>', {}];
                });
....

But the testValue variable defined above the httpBackendMock object isn't visible inside the run() function at all, but will be 'undefined'.

My understanding is that 'var' defined variables in JS are available to inner-scoped code, but that's not happening here. Is there some way to get variables to work inside there?

2

There are 2 answers

0
Keith Tyler On

The answer is to pass in a nested array of values and add an argument to the function signature of the mockmodule object.

var httpBackendMock = function(args) {
    var isFoo=args[0];
    var isBar=args[1];
...
browser.addMockModule('httpBackendMock', httpBackendMock, [['foo','bar']]);

Found the answer at: Protractor addMockModule additional arguments not working?

0
Estus Flask On

This piece of code

var testValue=randomValue();

is executed in Node. And this piece of code

function() {
    angular.module('httpBackendMock', ['ngMockE2E', 'name.of.app'])
    ...
}

is converted to string, passed to client side and executed in browser.

Outer function scope is not available in inner function, this explains why testValue is undefined in httpBackendMock function, and it will throw an error if httpBackendMock function uses strict mode.

Additional data can be passed through executeScript and addMockModule extra arguments, which will be available on client side.

As it is shown in documentation, the arguments after the first two are passed to the browser.

It should be something like

var httpBackendMock = function(testValue) {
    angular.module('httpBackendMock', ['ngMockE2E', 'name.of.app'])
    ...
}
...
var testValue=randomValue();
browser.addMockModule('httpBackendMock', httpBackendMock, testValue);