Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing JS scope elements/variables with Protractor

I have a Protractor test that enters login data and clicks the login button and I wish to check the value of an Angular variable.

The ng-click for the clicked element is doLogin() which is defined in the controller file as:

$scope.doLogin  = function(){
        console.log('login -- todo');
        // remember email used
        localStorageService.add('lastKeyEmail', $scope.data.login.key.email);
        // todo - make dynamic
        $scope.authentication.user = true;
        // set email of logged in user
        // todo: would need to be done in user service (set user details received from server)
        Authentication.setEmail($scope.data.login.key.email);
        // overwrite password in memory
        $scope.data.login.password = "thispasswordisdeletedsoyoucantreadit";
    };

How do I use Protractor's expect() on the value of $scope.authentication.user?

like image 425
Tahsis Claus Avatar asked Dec 23 '14 20:12

Tahsis Claus


2 Answers

There is a function called evaluate that allows you to evaluate an angular expressions given an element.

Select a DOM element for which you want to examine the scope, then call evaluate. There is an example in the documentation:

http://angular.github.io/protractor/#/api?view=ElementArrayFinder.prototype.evaluate

like image 71
Andres D Avatar answered Oct 24 '22 19:10

Andres D


With protractor, you execute end-to-end tests (like if you were a user clicking on the interface - buttons, anchors - and reading what's rendered on - what you decide to finally expose to the view), you don't have access to the JavaScript variables encapsulated inside your controllers.

The kind of test you're talking about is a unit test, where you only test your doLogin function, by injecting a $scope object populated with the proper data and then you assert that it does exactly what you expected by testing js variables.

Although, if $scope.authentication.user modifies the view when set to true (like if you display "Authentication successfull", or even route to an other view), you can assert with protractor that this behavior went through (by checking the "Authentication successfull" message in the DOM after you triggered the loggin) - but keep in mind this is still e2e testing.

like image 5
topheman Avatar answered Oct 24 '22 20:10

topheman