Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate when a checkbox is checked in AngularJS e2e tests?

I've been trying out the AngularJS e2e tests and am getting stuck determining whether or not a checkbox is checked.

I used the end to end test for the checkbox input as a sample (see the End to end test tab in the Example).

Html snippet:

Value1: <input type="checkbox" ng-model="value1"> <br/>

Controller snippet:

function Ctrl($scope) {   $scope.value1 = true; } 

Here is what I tried:

1) expect(binding('value1')).toEqual('true');

This works in the sample end to end test as long as value1 is displayed on screen with {{value1}}. If you test this locally and remove `{{value1}} the binding test fails. In most of my real-world examples I am not displaying the checkbox value on the screen anywhere.

2) expect(input('value1').val()).toEqual('true');

The value will always default to on and is not related to whether or not the checkbox is in a checked state (taken from this post).


Note: It looks like the Angular E2E testing will be replaced with Protractor in the future (see the docs)

like image 485
Gloopy Avatar asked Sep 18 '12 21:09

Gloopy


People also ask

How do I check if a checkbox is checked in AngularJS?

The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radio button to true or false. If the expression inside the ng-checked attribute returns true then the checkbox/radio button will be checked otherwise it will be unchecked.

How do you check checkbox is checked or not in angular 7?

Just define an ng-model directive in the checkbox and to find checkbox checked or not check model return value (TRUE or FALSE). If it has TRUE means checkbox is been checked.


2 Answers

For anyone using Protractor, there is webdriver isSelected() for exactly this.

Instead of asking for checked attribute you can do:

expect(element(by.model('value1')).isSelected()).toBeTruthy(); 
like image 59
Leo Gallucci Avatar answered Sep 30 '22 18:09

Leo Gallucci


I upvoted this question as I had the same issue. I used following workaround in my test, but I'm hoping to see the better way.

expect( element('input[ng-model="value1"]').attr('checked') ).toBeTruthy(); 
like image 38
Tosh Avatar answered Sep 30 '22 19:09

Tosh