测试方法是否返回Promise

tus*_*ath 4 unit-testing promise angularjs

在angularjs中,在测试服务时,我想检查返回的对象是否是Promise.

现在我正在做以下事情 -

 obj.testMethod()
        .should.be.instanceOf($q.defer());
Run Code Online (Sandbox Code Playgroud)

Flo*_*ine 12

测试对象是否是一个承诺很简单:

return !!obj.then && typeof obj.then === 'function';
Run Code Online (Sandbox Code Playgroud)

而已.如果一个对象有then方法,那就是一个承诺.

看起来棱角分明的$ q没有任何东西可以将它与其他类型的承诺区分开来.

  • 在我看来,这是更正确的方法,因为$ q本身会以`.then`作为承诺来对待任何东西. (3认同)

Fab*_*ook 8

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

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
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:

要测试" HttpPromise",您可以添加检查error以及success$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
}
Run Code Online (Sandbox Code Playgroud)

额外:

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

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

TypeError: Expecting a function in instanceof check, but got #<Object>