我们使用js-data
和js-data-angular
在我们的项目中。
我有以下模型:
(function () {
'use strict';
angular.module('dash.models')
.factory('Diagnosis', ['DS', function (DS) {
function transform(resourcename, attrs, cb) {
attrs.icd9codes.forEach(function (el) {
delete el.add;
});
cb(null, attrs);
}
this.transform = transform;
return DS.defineResource({
name: 'diagnosis',
idAttribute: 'id',
endpoint: '/diagnosis',
baseUrl: '/api',
beforeCreate: transform,
beforeUpdate: transform
});
}]);
}());
以及对所述模型的以下调用:
var startEditing = self.startEditing = function(parentScope, diagnosis) {
Diagnosis.findAll({
deep:true
}, {
endpoint: '/diagnosis/' + diagnosis.id
}).then(function(d) {
$scope.diagnosis = d;
$scope.inScope = true;
});
};
在我的单元测试中,我像这样模拟调用:
var diagDeferred = _$q_.defer();
diagDeferred.resolve({
'name': 'Breast',
'categories': null,
'id': '026c7cd0-14ef-4312-a8f1-2092107b0e50',
'icd9codes': [{id: '1', code: '001', description: 'ICD9 Code'}]
});
spyOn(Diagnosis, 'findAll').and.returnValue(diagDeferred.promise);
实际的调用是模拟的,没有被执行的(并且我找不到任何关于如何完成此操作的可靠信息)是 .then
内的函数Diagnosis.findAll
的
我知道代码可以工作,但我需要用单元测试来覆盖它,而我却一无所获。
谢谢。
最佳答案
我认为您忘记在测试中调用 $scope.digest()
。这是一个工作fiddle 。
在调用 startEditing()
后,您应该调用 $scope.$digest()
以便执行您的模拟 promise
并且您可以在 then
block 中获取您的数据。希望对您有所帮助。
关于angularjs - js-data-Angular 模型中的单元测试 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30175596/