我已经创建了一个存储回调函数的服务。当发生角度调整大小和/或方向改变事件时,将调用存储的回调。
我想在Jasmine中为这项服务编写一些测试。 有一个 addCallback 方法。这存储了回调函数。我创建了这个测试用例,但我不知道如何检查'print2'函数被调用。
describe('Testing Resize-updater service',function(){
var resizeUpdater;
var $window;
beforeEach(module('app.services'));
beforeEach(inject(function(_resizeUpdater_,_$window_){
resizeUpdater = _resizeUpdater_;
$window = _$window_;
}));
describe('Add a Callback and resize event',function(){
var change;
it('Test 1',inject(function(){
var $timeout = _$timeout_;
$window.innerWidth = 1368;
$window.innerHeight = 768;
function print2(){
change = "called"
}
resizeUpdater.addCallback(print2);
$window.innerWidth = 1300; //this trigger resize event
expect(change).toBe("called");
}));
});
});
以下是完整的服务代码:
(function() {
'use strict';
angular
.module('app.services')
.factory('resizeUpdater', ['$window','$q','$timeout','$log',UpdaterService ]);
function UpdaterService($window, $q, $timeout, $log){
var api = {};
var size = {
width: undefined,
height: undefined,
orientation: undefined
};
api.getSize = function(){
size.width = $window.innerWidth;
size.height = $window.innerHeight;
size.orientation = (function(){
if (size.width >= size.height){
return "landscape";
} else {
return "portrait";
}
})();
return size;
};
api.list = [];
api.addCallback = function(callback) {
api.list.push(callback);
};
api.removeCallback = function(callback){
var index = api.list.indexOf(callback);
delete api.list[index];
};
/*private method*/
var runAll = function() {
for(var item in api.list){
var obj = new Obj(api.list[item]);
obj.execute();
}
};
function Obj(callback) {
this.promise = undefined;
this.callback = callback;
this.execute = function () {
var defer = $q.defer();
this.callback(function (response) {
if (response === 'error') {
defer.reject('Error occured.');
$log.error('Failed - '+ callback.name + ' - ' + (new Date).toString());
} else {
defer.resolve(response);
}
});
this.promise = defer.promise;
this.promise.then(function(result){
$log.log('Executed - '+ callback.name + ' - ' + (new Date).toString());
});
};
}
angular.element($window).on('resize',(function(){
var timer_promise;
return function(){
if (timer_promise) {
$timeout.cancel(timer_promise);
}
timer_promise = $timeout(function(){
runAll();
}, 500);
};
})());
return api;
}})();
答案 0 :(得分:0)
您可以使用sinon
var print2 = sinon.spy();
resizeUpdater.addCallback(print2);
$window.innerWidth = 1300;
expect(print2.called).toBe(true);
答案 1 :(得分:0)
好的,你的测试看起来不错但你应该手动触发调整大小事件,然后运行一个摘要周期:
$window.innerWidth = 1000;
angular.element($window).triggerHandler('resize');
$scope.$digest();
$timeout.flush();
最好使用茉莉花间谍:
var spy = jasmine.createSpy('spy');
resizeUpdater.addCallback(spy);
// .... code
expect(spy).toHaveBeenCalled();