I am just starting with angular and I wanted to write some simple unit tests for my controllers, here is what I got.
app.js:
'use strict';
// Declare app level module which depends on filters, and services
angular.module('Prototype', ['setsAndCollectionsService']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/dashboard', {templateUrl: 'partials/dashboard.html', controller: 'DashboardController'});
$routeProvider.when('/setsAndCollections', {templateUrl: 'partials/setsAndCollections.html', controller: SetsAndCollectionsController});
$routeProvider.when('/repetition', {templateUrl: 'partials/repetition.html', controller: RepetitionController});
$routeProvider.otherwise({redirectTo: '/dashboard'});
}]);
and controllers.js
'use strict';
/* Controllers */
var myApp = angular.module('Prototype');
myApp.controller('DashboardController', ['$scope', function (scope) {
scope.repeats = 6;
}]);
/*function DashboardController($scope) {
$scope.repeats = 5;
};*/
function SetsAndCollectionsController($scope, $location, collectionsService, repetitionService) {
$scope.id = 3;
$scope.collections = collectionsService.getCollections();
$scope.selectedCollection;
$scope.repetitionService = repetitionService;
$scope.switchCollection = function (collection) {
$scope.selectedCollection = collection;
};
$scope.addCollection = function () {
$scope.collections.push({
name: "collection" + $scope.id,
sets: []
});
++($scope.id);
};
$scope.addSet = function () {
$scope.selectedCollection.sets.push({
name: "set" + $scope.id,
questions: []
});
++($scope.id);
};
$scope.modifyRepetition = function (set) {
if (set.isSelected) {
$scope.repetitionService.removeSet(set);
} else {
$scope.repetitionService.addSet(set);
}
set.isSelected = !set.isSelected;
};
$scope.selectAllSets = function () {
var selectedCollectionSets = $scope.selectedCollection.sets;
for (var set in selectedCollectionSets) {
if (selectedCollectionSets[set].isSelected == false) {
$scope.repetitionService.addSet(set);
}
selectedCollectionSets[set].isSelected = true;
}
};
$scope.deselectAllSets = function () {
var selectedCollectionSets = $scope.selectedCollection.sets;
for (var set in selectedCollectionSets) {
if (selectedCollectionSets[set].isSelected) {
$scope.repetitionService.removeSet(set);
}
selectedCollectionSets[set].isSelected = false;
}
};
$scope.startRepetition = function () {
$location.path("/repetition");
};
}
function RepetitionController($scope, $location, repetitionService) {
$scope.sets = repetitionService.getSets();
$scope.questionsLeft = $scope.sets.length;
$scope.questionsAnswered = 0;
$scope.percentageLeft = ($scope.questionsLeft == 0 ? 100 : 0);
$scope.endRepetition = function () {
$location.path("/setsAndCollections");
};
}
now I am in process of converting global function controllers to ones defined by angular API as you can see by example of DashboardController.
Now in my test:
describe("DashboardController", function () {
var ctrl, scope;
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('DashboardController', {$scope: scope});
}));
it("has repeats attribute set to 5", function () {
expect(scope.repeats).toBe(5);
});
});
I am getting
Error: Argument 'DashboardController' is not a function, got undefined
I am wondering then, where is my mistake? If I understand this right, ctrl = $controller('DashboardController', {$scope: scope}); should inject my newly created scope to my DashboardController to populate it with attributes - in this case, repeats.
You need to set up your Prototype module first.
beforeEach(module('Prototype'));
Add that to your test, above the current beforeEach would work.
describe("DashboardController", function () {
var ctrl, scope;
beforeEach(module('Prototype'));
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('DashboardController', {$scope: scope});
}));
it("has repeats attribute set to 5", function () {
expect(scope.repeats).toBe(5);
});
});
Related
I have the following situation:
controller.js
controller('PublishersCtrl',['$scope','APIService','$timeout', function($scope,APIService,$timeout) {
APIService.get_publisher_list().then(function(data){
});
}));
controllerSpec.js
'use strict';
describe('controllers', function(){
var scope, ctrl, timeout;
beforeEach(module('controllers'));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new(); // this is what you missed out
timeout = {};
controller = $controller('PublishersCtrl', {
$scope: scope,
APIService: APIService,
$timeout: timeout
});
}));
it('should have scope variable equals number', function() {
expect(scope.number).toBe(3);
});
});
Error:
TypeError: Object #<Object> has no method 'get_publisher_list'
I also tried something like this, and it didn't work:
describe('controllers', function(){
var scope, ctrl, timeout,APIService;
beforeEach(module('controllers'));
beforeEach(module(function($provide) {
var service = {
get_publisher_list: function () {
return true;
}
};
$provide.value('APIService', service);
}));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
timeout = {};
controller = $controller('PublishersCtrl', {
$scope: scope,
APIService: APIService,
$timeout: timeout
}
);
}));
it('should have scope variable equals number', function() {
spyOn(service, 'APIService');
scope.get_publisher_list();
expect(scope.number).toBe(3);
});
});
How can i solve this? any suggestions?
There are two ways (or more for sure).
Imagining this kind of service (doesn't matter if it is a factory):
app.service('foo', function() {
this.fn = function() {
return "Foo";
};
});
With this controller:
app.controller('MainCtrl', function($scope, foo) {
$scope.bar = foo.fn();
});
One way is just creating an object with the methods you will use and spy them:
foo = {
fn: function() {}
};
spyOn(foo, 'fn').andReturn("Foo");
Then you pass that foo as a dep to the controller. No need to inject the service. That will work.
The other way is to mock the service and inject the mocked one:
beforeEach(module('app', function($provide) {
var foo = {
fn: function() {}
};
spyOn(foo, 'fn').andReturn('Foo');
$provide.value('foo', foo);
}));
When you inject then foo it will inject this one.
See it here: http://plnkr.co/edit/WvUIrtqMDvy1nMtCYAfo?p=preview
Jasmine 2.0:
For those that struggle with making the answer work,
as of Jasmine 2.0 andReturn() became and.returnValue()
So for example in the 1st test from the plunker above:
describe('controller: MainCtrl', function() {
var ctrl, foo, $scope;
beforeEach(module('app'));
beforeEach(inject(function($rootScope, $controller) {
foo = {
fn: function() {}
};
spyOn(foo, 'fn').and.returnValue("Foo"); // <----------- HERE
$scope = $rootScope.$new();
ctrl = $controller('MainCtrl', {$scope: $scope , foo: foo });
}));
it('Should call foo fn', function() {
expect($scope.bar).toBe('Foo');
});
});
(Source: Rvandersteen)
I'm pretty new to angular and been wanting to test drive and I've hit a snag mocking out $window. The item in which I'm attempting to test is very simple but important -- I need to know if localStorage is there or not and need to be able to fake out $window to do so.
The code is very basic so far and what I have is this for the service ...
'use strict';
mainApp.factory('somedataStorage',function($window) {
var local = $window.localStorage;
return {
hasLocal: function() {
return local != undefined;
},
};
});
How I'm testing it is this ...
(function () {
var fakeWin = {
localStorage: null
};
var $injector = angular.injector(['ngMock', 'ng', 'mainApp']);
//var $window = $injector.get('$window');
var init = {
setup: function () {
//this.$window = fakeWin;
},
}
module('LocalStorageTests', init);
test("if localstorage isn't there, say so", function () {
var $service = $injector.get('somedataStorage' /*, {$window: fakeWin} */);
ok(!$service.hasLocal, "no local storage");
});
})();
So what am I missing?
I still have the problem with jQuery datepicker in Emberjs. This is my code
If I go away from page with my datepicker, a console gave me error: ui.destroy is not a function.
JQ.Widget = Em.Mixin.create({
didInsertElement: function () {
"use strict";
var options = this._gatherOptions(), ui;
this._gatherEvents(options);
if (typeof jQuery.ui[this.get('uiType')] === 'function') {
ui = jQuery.ui[this.get('uiType')](options, this.get('element'));
} else {
ui = this.$()[this.get('uiType')](options);
}
this.set('ui', ui);
},
willDestroyElement: function () {
"use strict";
var ui = this.get('ui'), observers, prop;
if (ui) {
observers = this._observers;
for (prop in observers) {
if (observers.hasOwnProperty(prop)) {
this.removeObserver(prop, observers[prop]);
}
}
ui._destroy();
}
},
_gatherOptions: function () {
"use strict";
var uiOptions = this.get('uiOptions'), options = {};
uiOptions.forEach(function (key) {
options[key] = this.get(key);
var observer = function () {
var value = this.get(key);
this.get('ui')._setOption(key, value);
};
this.addObserver(key, observer);
this._observers = this._observers || {};
this._observers[key] = observer;
}, this);
return options;
},
_gatherEvents: function (options) {
"use strict";
var uiEvents = this.get('uiEvents') || [], self = this;
uiEvents.forEach(function (event) {
var callback = self[event];
if (callback) {
options[event] = function (event, ui) { callback.call(self, event, ui); };
}
});
}
});
Ember calls willDestroyElement function, but "ui._destroy() is not a function" Why?
This code works fine with outher jQuery elements (Autocomplete,Button ...)
I've had success with the following change:
Replace:
ui._destroy();
With:
if (ui._destroy) ui._destroy();
else if (ui.datepicker) ui.datepicker('destroy');
You may have to add more code if you want to support more UI controls that don't have _destroy().
How can I unit test this knockoutjs binding where I call a certain function 'myValueAccessor' when the element is swiped on my touchpad?
I am also unsure what the unit should or is able to test at all here.
It would be ok for the first time to assert wether myValueAccessor is called.
But how can I trigger/imitate or should I say mock... the swiperight event?
ko.bindingHandlers.tap = {
'init': function (element, valueAccessor) {
var value = valueAccessor();
var hammertime1 = Hammer(element).on("swiperight", function (event) {
$(element).fadeOut('fast', function () {
value();
});
});
}
};
self.myValueAccessor = function () {
location.href = 'set a new url'
};
UPDATE
I have put here my unit test with mocha.js
I can outcomment the 'value()' in the binding but still the test succeeded thats odd.
Is it not correct to put this (as a test):
function (element,args) {
alert('assertion here');
}
as a 3rd parameter into the ko.test function?
ko.bindingHandlers.tap = {
'init': function (element, valueAccessor) {
var value = valueAccessor();
var hammertime1 = $(element).on("swiperight", function (event) {
$(element).fadeOut('fast', function () {
//value();
});
});
}
};
// Subscribe the swiperight event to the jquery on function
$.fn.on = function (event, callback) {
if (event === "swiperight") {
callback();
}
};
// Subscribe the fadeOut event to the jquery fadeOut function
$.fn.fadeOut = function (speed, callback) {
callback();
};
ko.test("div", {
tap: function () {
assert.ok(true, "It should call the accessor");
}
}, function () {
});
UPDATE:
custom.bindings.js:
define(['knockout','hammer'], function (ko,Hammer) {
return function Bindings() {
ko.bindingHandlers.tap = {
'init': function (element, valueAccessor) {
var value = valueAccessor();
var hammertime1 = Hammer(element).on("swiperight", function (event) {
$(element).fadeOut('fast', function () {
value();
});
});
}
};
};
});
unittest.js:
how can I connect this code to knockout in my test?
UPDATE
The Bindings is injected via require.js from my bindings.js file:
describe("When swiping left or right", function () {
it("then the accessor function should be called", function () {
ko.bindingHandlers.tap = new Bindings();
Hammer.Instance.prototype.on = function (event, callback) {
if (event === "swiperight") {
callback();
}
};
$.fn.fadeOut = function (speed, callback) {
callback();
};
var accessorCalled = false;
ko.test("div", {
tap: function () {
accessorCalled = true;
}
}, function () {
assert.ok(accessorCalled, "It should call the accessor");
});
});
});
bindings.js
define(['knockout','hammer'], function (ko,Hammer) {
return function () {
return {
'init': function (element, valueAccessor) {
var value = valueAccessor();
var hammertime1 = Hammer(element).on("swiperight", function (event) {
$(element).fadeOut('fast', function () {
value();
});
});
}
};
};
});
myviewmodel.js
...
ko.bindingHandlers.tap = new Bindings();
...
You can check my binding collection for how to test
https://github.com/AndersMalmgren/Knockout.Bindings/tree/master/test
This is my function that all my tests using
ko.test = function (tag, binding, test) {
var element = $("<" + tag + "/>");
element.appendTo("body");
ko.applyBindingsToNode(element[0], binding);
var args = {
clean: function () {
element.remove();
}
};
test(element, args);
if (!args.async) {
args.clean();
}
};
edit: Sorry forgot mocking, you just do
$.fn.on = function() {
}
I do not know what exact logic you want to test in that code since there hardly is any, but something like this
http://jsfiddle.net/Akqur/
edit:
May you get confused where i hook up your binding? Its done here
{
tap: function() {
ok(true, "It should call the accessor");
}
}
I tell ko to hook up a "tap" binding and instead of hooking in up to a observable I use a mocking function, when your custom bindnig calls value() from the fadeout function the test assert will fire
edit:
Maybe this approuch makes more sense to you?
http://jsfiddle.net/Akqur/5/
Note that it only works if your code is executed synchronous
edit:
Here i use the third argument of ko.test
http://jsfiddle.net/Akqur/8/
I have a controller with a local variable
function IndexCtrl($scope) {
var pagesById = [];
loadPages();
// snip
function loadPages() {
// pagesById gets populated
}
// snip
}
I'd like to test that pagesById is correctly populated but I'm not sure how to get at it from my it(). I don't need this variable to be in the $scope, it's just an intermediate set of information, so if I can avoid adding it to $scope that would be ideal.
it('scope.pages should populated based on pages data.', function() {
$httpBackend.flush();
expect(pagesById).toEqualData(mock_page_results);
});
gives me
ReferenceError: pagesById is not defined
Do I have any other options besides attaching it to $scope?
In your jasmine spec, first create the controller:
var ctrl;
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('myController', {
$scope: scope
});
}));
Then you can access its properties by doing ctrl.pagesById. Of course, rather than doing var pagesById you'll need to use this.pagesById in your controller.
Here is my way for testing local variables in Angular methods:
//------- Function for getting value of local variables
function getLocalVariable(sLocalVarName, obj, method, args){
method = method.toString();
let changedMethod = method.substring(0, method.lastIndexOf("}")) + ";" + "return " + sLocalVarName + "}";
eval(' changedMethod = ' + changedMethod);
return changedMethod.call(obj, args)
}
//----------- service
class assignStuffService {
getAvaliableStuff(shift) {
const params = {
agency_id: 0 ,
start_time: shift.data.shift.start_time,
end_time : shift.data.shift.end_time
};
}
}
//----------- part of spec
it('should set values to "params" object props', () => {
let shift = {
data:{
shift:{
start_time:'',
end_time:''
}
}
};
let params = getLocalVariable('params',
assignStuffService,
assignStuffService.getAvaliableStuff,
shift);
expect(params).toEqual({
agency_id: 0 ,
start_time: shift.data.shift.start_time,
end_time : shift.data.shift.end_time
});
});