gpt4 book ai didi

angularjs - 如何在 AngularJS 中模拟包含资源的服务

转载 作者:行者123 更新时间:2023-12-04 00:52:21 25 4
gpt4 key购买 nike

我有一个包含这样的资源工厂的服务:

serviceModule.factory('ProjectResource', ['$resource', function($resource){
return $resource('/projects/:id.json', {}, {
'query': {method: 'GET', isArray: true}}
);
}]);

在一个位于 Controller 中的表单中,我注入(inject)了 serviceModule,并创建了资源对象的一个​​新实例:
  $scope.project = new ProjectResource({name: 'Enter a name'})

我有一些 mock 它的问题。我尝试过创建一个像这样的模拟对象,并将其注入(inject) Controller 中:
 mockProjectResource = {
query: function(){
deferred = $q.defer();
deferred.resolve({id: 1, :name:'test'});
return deferred.promise;
}
};

无论单元测试如何,我都会收到错误消息:
TypeError: undefined is not a function

它指向项目资源对象 ( $scope.project = new ProjectResource({name: 'Enter a name'})) 的初始化。

有什么好的方法来模拟 new ProjectResource(...) ?

最佳答案

模拟基于资源的服务的另一种方法是这样的:

// the name of an object should start with a capital letter
// in the case where we create a function object (as opposed to
// a literal object).
MockProjectResource = function(){};

// we add the "query" method to the "prototype" property
MockProjectResource.prototype.query = function(){
deferred = $q.defer();
deferred.resolve({id: 1, :name:'test'});
return deferred.promise;
};

像上面那样模拟查询函数适用于 Controller 期望作为调用结果返回的 promise ,例如:
var projectController = angular.module('projectController', []);
projectController.controller('ProjectController', ['$scope', 'ProjectResource',
function($scope, ProjectResource) {

var promise = ProjectResource.query();
promise.then(function(data) {
console.log(data);
},
function(err){
console.log(err);
});

}]);

但是,如果 Controller 希望在回调中发送结果,如下所示:
      ProjectResource.query(function(data) {
console.log(data);
},
function(err){
console.log(err);
});

然后,需要像这样模拟服务:
MockProjectResource.prototype.query = function(success, error){
var deferred = q.defer();
var promise = deferred.promise;
promise.then(success, error);
deferred.resolve({id: 1, :name:'test'});
};

有关完整示例,请参阅我对类似问题的回答:

How do you mock an angularjs $resource factory

关于angularjs - 如何在 AngularJS 中模拟包含资源的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24381698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com