Angularjs 使用jasmine测试指令时无法解决的承诺
我目前正在测试一个使用承诺的自定义指令 指令第一部分代码段的结构如下:Angularjs 使用jasmine测试指令时无法解决的承诺,angularjs,jasmine,promise,when-js,Angularjs,Jasmine,Promise,When Js,我目前正在测试一个使用承诺的自定义指令 指令第一部分代码段的结构如下: angular.module('app').directive('simpleMock', [ '$q', function ($q) { 'use strict'; return { link: function ($scope) { $scope.$watch('acc.mockPromise', function (promise) {
angular.module('app').directive('simpleMock', [
'$q',
function ($q) {
'use strict';
return {
link: function ($scope) {
$scope.$watch('acc.mockPromise', function (promise) {
var sF;
$scope.sF = sF = {};
promise.then(function (res) {
sF.res = res;
return $q.when(res.fetchData());
}).then(function (data) {
sF.data = data;
return $q.when(sF.res.fetchLinks('create'));
}).then(function (links) {
if (!links.length) {
return $q.when(sF.res.fetchLinks('edit'));
}
return links;
})....
...............
我编写的jasmine测试规范具有以下结构:
beforeEach(module('app'));
beforeEach(inject(function ($rootScope, $compile) {
when = modulejs.require('when');
sF = {};
res = jasmine.createSpyObj('res', ['fetchData', 'fetchLinks']);
sF.res = res;
res.fetchData.andReturn(when([{
href: 'http://promise.angularjs.com/',
name: 'undefined',
rel: 'rel',
title: "Fake link"
}]));
res.fetchLinks.andReturn(when([{
href: 'http://promise.angularjs.com/',
name: 'undefined',
rel: 'rel',
title: "Fake link"
}]));
compile = function (acc, res) {
var $childScope, $parentScope, element;
element = angular.element('<div simple-mock></div>');
$parentScope = $rootScope.$new();
$parentScope.acc = acc;
acc.mockPromise = res;
$childScope = $parentScope.$new();
$compile(element)($childScope);
$parentScope.$digest();
return $childScope;
};
getRootScope = function () {
return $rootScope;
}
}));
it('calls fetchData', function () {
var $scope, acc, $rootScope;
acc = {};
$scope = compile(acc, when(res));
$rootScope = getRootScope();
$scope.$apply();
$rootScope.$apply();
$rootScope.$apply();
$rootScope.$apply();
$scope.acc.mockPromise.then(function () {
expect($scope.sF.res.fetchData).toHaveBeenCalled();
});
[但是,控件会一直插入到上一行代码中。]
这个问题的一个可能原因可能是承诺没有得到解决。
此外,不会引发任何错误或异常。
解决规范中“何时”承诺的任何建议-以便控制进入指令的以下部分:
}).then(function (data) {
sF.data = data;
return $q.when(sF.res.fetchLinks('create'));
}).then(function (links) {
if (!links.length) {
return $q.when(sF.res.fetchLinks('edit'));
}
return links;
})
您必须使用rootsScope.Digest查看可能的副本
}).then(function (data) {
sF.data = data;
return $q.when(sF.res.fetchLinks('create'));
}).then(function (links) {
if (!links.length) {
return $q.when(sF.res.fetchLinks('edit'));
}
return links;
})