Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock angular.module('myModule', []).value() in Jasmine/Protractor

I'm trying to use Protractor's addMockModule() to mock a simple AngularJS module and override a variable:

Here is my HTML:

<body ng-app="myApp">
    <div  ng-controller="myAppController">    
        Overriden module value <b>{{myValue}}</b>
    </div>

    <script src="/Scripts/Lib/angular/angular.js"></script>
    <script src="/module.js"></script>
    <script src="/controller.js"></script>
</body>

Here is my Controller:

var myApp = angular.module("myApp", ['myModule']);

myApp.controller("myAppController", function ($scope, myValue) {
    $scope.myValue = myValue;
});

Here is my Module:

var newModule = angular.module('myModule', []);
newModule.value('myValue', "oldValue");

Here is my Jasmine/Protractor code:

var mockMyModule = function () {
        var newModule = angular.module('myModule', []);
        newModule.value('myValue', "newMockedValue");
    };

    it('should override services via mock modules', function () {

        ptor = protractor.getInstance();
        ptor.ignoreSynchronization = true;
        browser.addMockModule('portfolioDataAccessMod', mockMyModule);
        browser.get('http://localhost:57627/page1.html');

        expect(element(by.binding("myValue")).getText()).toBe("newMockedValue");

    });

Results:

Failures:

1) End-to-end test in /AssetAllocation/Index should override services via mock modules Message: Expected 'oldValue' to be 'newMockedValue'.

What is wrong ?

All samples I have found so far are to override HTTP calls, but all I want is to mock a very simple module with a simple variable. Is it possible to do in Protractor ?

like image 894
Leandro Gomes Avatar asked Jul 02 '14 23:07

Leandro Gomes


1 Answers

According to Juliemr in this post:

https://github.com/angular/protractor/issues/509

" the code that is run in the mockedModule is run in a separate context from the test. One is in the browser, one is in the node.js process running the test "

Put declaration of mockedValue inside it() and enable angular synchronization

it('should override services via mock modules', function () {
    ptor = protractor.getInstance();

    // When ignoreSynchronization is true mocking doesn't work
    ptor.ignoreSynchronization = false; 

    browser.addMockModule('myModule', function () {
        var module = angular.module('myModule').config(['$provide', function ($provide) {
            $provide.constant('myValue', 'newMockedValue');
        }])
    });

    browser.get('http://localhost:57627/page1.html');
    expect(element(by.binding("myValue")).getText()).toBe("newMockedValue");

});
like image 134
Leandro Gomes Avatar answered Nov 15 '22 05:11

Leandro Gomes