Software QA FYI - SQAFYI

Testing Two-Way Data Binding in AngularJS

By: Dr. Yoram Kornatzky

Once you accumulate controllers and directives you can then begin to use various libraries such as High Charts. You will then need to test that two-way data binding works across all these constructions.

Testing data-binding with explicit user actions such as filling input boxes or clicking buttons is cumbersome and requires littering your web application screens with testing artifacts.

The following will describe some cleaner techniques.
Periodic Data Change
One alternative approach, that was used in several projects, is to have your controller/directive code modify your data periodically with an ‘$interval’ AngularJS ‘setInterval’:
$interval(function(){ $scope.value = Math.random(100); }, 300);

$interval(function(){
$scope.value = Math.random(100);
}, 300);


where in your ux, you have:
<div>{{value}}</div>

There is nothing more exciting than to see the data changing before your eyes every so often.

When using libraries, for example visualization libraries, you need to use structured data such as a time series. Therefore you will periodically need to generate random data:
$scope.a = [10.2, -0.45, 5.6, 2.3, -1.8, 7.2, 8.5]; $interval(function(){
$scope.value = _.sample($scope.a); }, 300);

$scope.a = [10.2, -0.45, 5.6, 2.3, -1.8, 7.2, 8.5];
$interval(function(){
$scope.value = _.sample($scope.a);
}, 300);


where the Underscore sample function was used to sample the array.

The data is then used with High Charts:



where in your controller you have:
$scope.chartConfig = { // many options omitted here //Series objects series: [{
data: $Scope.a, type: 'spline' }] };

$scope.chartConfig = {
// many options omitted here
//Series objects
series: [{
data: $Scope.a,
type: 'spline'
}]
};


Periodically you can change the data in a random way with:
$interval(function(){ $scope.chartConfig.series.splice(0,1, { data: _.sample($scope.a), type: 'spline' }); }, 300);

$interval(function(){
$scope.chartConfig.series.splice(0,1, {
data: _.sample($scope.a), type: 'spline'
});
}, 300);


Watches

On the flip side, when directives involving form elements, such as an input elements, are used you need to test that two-way data binding works across a call chain of directives and controllers.

Full article...


Other Resource

... to read more articles, visit http://sqa.fyicenter.com/art/

Testing Two-Way Data Binding in AngularJS