AngularJS Javascript Unit Test
▌Introduction
Wallaby.js is a javascript unit test runner.
You can go to the official Wallaby.js website for more reference. In this
article, I will make an example to test my AngularJS Controller in Visual
Studio 2015.
▌Environment
l AngularJS v1.4.8
l Wallaby.js
▌Samples
▋Download and install
Wallaby.js
▋Create Wallaby.js
Config
Under \Script folder, create a json file like
this.
{
"files": [
"Source/angularjs/angular.js",
"Source/angularjs/angular-route.js",
"Source/angularjs/angular-mocks.js",
"Dev/app/controllers/wallabySample.js"
],
"tests": [
"Dev/test/*.js"
]
}
|
You have to include
the three AngularJS js files and the javasctipts which you would like to test
in the array of "files".
Put your unit test javascript file in the array of "tests".
Okay, now
you can run the Wallaby.js. Right click the .json and choose 【Start Wallaby.js】
Wallaby.js
will download and install some dependencies in the first time.
If everything
is fine, you will see the message on console.
No failing tests, 0 passing.
|
▋Start writing the unit
tests
I
will take an existing AngularJS controller as our test target.
l JS
var app =
angular.module('app', [])
.controller('wallabySampleCtrl', function ($scope) {
$scope.Wishes = ['Happy Birthday!', 'Merry Xmas!', 'Happy New Year!'];
$scope.DropWishes = [];
$scope.DropSuccess = function ($event, index,
array) {
array.splice(index, 1);
};
$scope.OnDrop = function ($event, $data, array) {
if (array != null) {
array.push($data);
}
};
});
|
As you can
see, I am going to test the two functions :
$scope.DropSuccess
$scope.OnDrop
l Unit test js
In the unit
test, I inject the array : $scope.Wishes, as our testing data.
And the length of $scope.Wishes
is 3, so I expect that the OnDrop()
function will append a new element to $scope.Wishes and the
final length will be 4.
And the DropSuccess() removes an element
from $scope.Wishes, so I expect the length will be 2.
/*global describe,
it, beforeEach, inject, expect*/
(function () {
'use strict';
describe('Wishes array', function () {
var ctrl,scope;
beforeEach(module('app'));
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
ctrl = $controller('wallabySampleCtrl', {
$scope : scope
});
}));
it('should
be length 4 after adding an element', function () {
scope.OnDrop(null, 'Good Job!', scope.Wishes);
expect(scope.Wishes.length).toBe(4);
});
it('should
be length 2 after removing an element', function () {
scope.DropSuccess(null, 2,
scope.Wishes);
expect(scope.Wishes.length).toBe(2);
});
});
}());
|
If what you
expect does not match the result, you will see the warning on the coding GUI.
All
of the them are real-time shown, and we can immediately know the problems or
errors on the javascripts.
▌Summary
Wallaby.js
is a real-time and powerful javascript unit test tool for many developement
IDE.
I
am thinking to have one J
▌Reference
沒有留言:
張貼留言