如果我在karma.conf.js中使用Chrome,我的因果报应单元测试会很好,但如果更改为PhantomJS,则会失



要测试的代码段:

$timeout(function() {
$http.get('/getUpdates.json')
.success(function(data, status, headers, config) {
})
.error(function(data, status, headers, config) {
})
.then(function(response) {
if (usingPopOverWait) {
$utilUi.hidePopOverWait();
}
var random = Math.floor((Math.random() * 4) + 1);
if (random === 3) {
deferred.reject('Error loading mock data');
}
else {
deferred.resolve(response.data.success);
}
});
}, 3000);

测试文件:

describe('Controller: CtrlHelp', function () {
beforeEach(module('nzrbTabApp'));
var CtrlHelp, scope, rootScope, location, timeout, httpBackend, modelHelp;
var mockResponseHelp =
{
'success' : {
'hasUpdates': true
},
'error': {
}
};
beforeEach(inject(function ($injector) {
httpBackend = $injector.get('$httpBackend');
timeout = $injector.get('$timeout');
modelHelp = $injector.get('$modelHelp');
}));
beforeEach(inject(function ($controller, $rootScope, $location) {
rootScope = $rootScope;
scope = $rootScope.$new();
location = $location;
CtrlHelp = $controller('CtrlHelp', {
$scope: scope,
$location: location
});
}));
it('Should load static content and attached to scope', function () {
httpBackend.whenGET('/getUpdates.json').respond(mockResponseHelp);
timeout.flush();
httpBackend.flush();
if (!scope.help.showError) {
//check a condition
}
});
});

Error: No deferred tasks to be flushed
at app/bower_components/angular-mocks/angular-mocks.js:121
at app/bower_components/angular-mocks/angular-mocks.js:1659
at test/spec/features/help/ctrl-help-test.js:91

该错误是在timeout.flush()行上引发的。当使用Chrome作为浏览器时,相同的代码运行得非常好。

如果需要更多的细节来帮助解决上述问题,请告诉我。

问候,

Mohit

这听起来像是一个时间问题,PhantomJS遇到了一个空队列,但Chrome在其中找到了一个函数。

这也是一个众所周知的奇怪之处,ngMock.$timeout的行为与此相同,将Error抛出一个空队列。解决方法是允许出现错误,必要时使用try-catch。

更新:以下代码适用于OS X上的PhantomJS 1.9.7(但我不知道deferred指的是哪个延迟对象。)所以听起来问题可能是测试中的代码,而不是测试本身。

var nzrbTabApp = angular.module("nzrbTabApp", []);
nzrbTabApp.controller("CtrlHelp", function ($scope, $timeout, $http) {
$timeout(function () {
$http.get('/getUpdates.json')
.success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config) {
})
.then(function (response) {
$scope.error = "Error loading mock data";
});
}, 3000);
});

带有测试

it('Should load static content and attached to scope', function () {
httpBackend.whenGET('/getUpdates.json').respond(mockResponseHelp);
timeout.flush();
httpBackend.flush();
expect(scope.error).toBeTruthy();
});   

相关内容

最新更新