下面,我有3个功能完全相同。每一个使用调用不同的方式setTimeout
,delay1()
使用setTimeout
直接,delay2()
用途angularjs$timeout
和delay3()
用途lodash debounce
。他们都工作正常。
当我使用Jasmine测试时会出现问题。setTimeout
正常工作与jasmine.clock().tick()
方法,但$timeout
并debounce
没有
我有兴趣与Jasmine合作进行反跳操作。我知道我可以使用$timeout.flush()
与angularjs但$timeout
和setTimeout
其他地方给我的问题,在我的代码中,我使用它与单张地图。防弹跳与传单效果很好。
我在这里创建了一个监听器:plnkr,在其中$timeout
,当setTimeout测试通过时,您将看到and反跳测试未通过。
有办法解决这个问题吗?谢谢
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $timeout) {
$scope.name = 'World';
$scope.delayed1 = function(){
setTimeout(function(){
$scope.name = "Hello world by setTimeout";
},500)
}
$scope.delayed2 = function(){
$timeout(function(){
$scope.name = "Hello world by $timeout";
},500)
}
$scope.delayed3 = function(){
_.debounce(function(){
$scope.name = "Hello world by debounce";
},500)
}
});
规格
describe('Testing a Hello World controller', function() {
var $scope = null;
var ctrl = null;
//you need to indicate your module in a test
beforeEach(module('plunker'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
ctrl = $controller('MainCtrl', {
$scope: $scope
});
}));
it('should say hallo to the World', function() {
expect($scope.name).toEqual('World');
});
it('should say Hello world by setTimeout', function() {
jasmine.clock().install();
$scope.delayed1();
jasmine.clock().tick(600);
expect($scope.name).toEqual('Hello world by setTimeout');
jasmine.clock().uninstall();
});
it('should say Hello world by timeout', function() {
jasmine.clock().install();
$scope.delayed2();
jasmine.clock().tick(600);
expect($scope.name).toEqual('Hello world by timeout');
jasmine.clock().uninstall();
});
it('should say Hello world by debouce', function() {
jasmine.clock().install();
$scope.delayed3();
jasmine.clock().tick(600);
expect($scope.name).toEqual('Hello world by debouce');
jasmine.clock().uninstall();
});
});
Jasmine中的时钟仅在您正在测试setInterval()
或setTimeout()
直接运行时才起作用,因为它只是模拟那些专门用于同步运行的功能。我相信有一个Jasmine来模拟Date对象的拉取请求,这将允许像_.debounce()
不模拟它一样测试功能,但是我不记得它是否被合并了。
要进行测试,_.debounce()
您必须模拟它以使其同步运行,最好是作为间谍运行,或者您可以重写该函数。这是我发现对我有用的东西:
spyOn(_, 'debounce').and.callFake(function (func) {
return function () {
func.apply(this, arguments);
};
});
现在,对的调用_.debounce()
将同步运行,并且测试应该成功完成。当然,您仍然必须使用$timeout.flush()
。
我通过以下更改更新了您的监听器:http ://plnkr.co/edit/KXmwcf1faUNf8nlqPeyd
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句