加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 测试方法是否返回Promise

发布时间:2020-12-17 18:01:47 所属栏目:安全 来源:网络整理
导读:在 angularjs中,在测试服务时,我想检查返回的对象是否是Promise. 现在我正在做以下事情 – obj.testMethod() .should.be.instanceOf($q.defer()); 解决方法 在$q( https://github.com/angular/angular.js/blob/master/src/ng/q.js#L248)的源代码中查看第248
在 angularjs中,在测试服务时,我想检查返回的对象是否是Promise.

现在我正在做以下事情 –

obj.testMethod()
        .should.be.instanceOf($q.defer());

解决方法

在$q( https://github.com/angular/angular.js/blob/master/src/ng/q.js#L248)的源代码中查看第248行,实际上没有一个检查可以确定.这将是你最好的选择

var deferred = method();

if(angular.isObject(deferred) && 
   angular.isObject(deferred.promise) && 
   deferred.promise.then instanceof Function && 
   deferred.promise["catch"] instanceof Function && 
   deferred.promise["finally"] instanceof Function){
   //This is a simple Promise
}

如果promise实际上是一个你可以使用新Promise()的函数,那么你就可以使用promise instanceof Promise,但它是一个对象,所以它没有任何特殊标识符,你可以测试的唯一东西就是它们的属性.

编辑:

要测试“HttpPromise”,您可以添加对$http服务(https://github.com/angular/angular.js/blob/master/src/ng/http.js#L726)中定义的错误和成功的检查:

var promise = $http(...);

if(angular.isObject(promise) && 
   promise.then instanceof Function && 
   promise["catch"] instanceof Function && 
   promise["finally"] instanceof Function && 
   promise.error instanceof Function && 
   promise.success instanceof Function){
   //This is a HttpPromise
}

额外:

如果你注意到$http实际上没有返回延迟,它会返回直接的承诺,如果你按照调用它实际上返回$q.when(…)并添加了几个函数.你可以看到$q.when没有返回延迟,而是返回$q.deferred().promise,所以反过来$http(…)永远不会是$q.deferred()

此外,如果您要运行您发布的测试,我希望您收到此错误:

TypeError:在instanceof check中期望一个函数,但得到#< Object>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读