AngularJS + 茉莉花 + 承诺句柄

AngularJS + Jasmine + handle of promises

我正在使用 angularjs 1.4jasmine 2.4

我正在尝试测试一个函数,我想让它return成为一个承诺,所以它上面的另一层可以处理可能的值。

我的问题是函数首先验证输入。如果他们不合适,我想return拒绝承诺否则它将做任何它必须做的事情并解决承诺

这是来自 emailSvc 的函数的一部分:

// Function found in the emailSvc
    this.sendEmail = function sendEmail(apiKey, token, email_type)
    {

      // Prerequisite to send email
      if(!apiKey) {
        return $q.when("apiKey not present.");
      }

      var deferred = $q.defer();

      // Ajax call
      serviceApiEmail.send(apiKey, token, email_type)
          .then(function(data){
              deferred.resolve(data);
          })
          .catch(function(e){
              deferred.reject(e);
          })

      return deferred.promise;
    }

我的测试用例如下:

        it('should reject sending email if apiKey is not present', function(){

          var rejectEmail;

          var apiKey,
              verifyToken = acceptedVerifyToken,
              emailType = const_EMAIL_TYPE.SIGNUP;

          i_emailSvc.sendEmail(apiKey, verifyToken, emailType)
            .then(function(){

              // It should not come here
              rejectEmail = false;

            }).catch(function(){

              rejectEmail = true;

            });

            // It comes here without executing any success or fail promise handlers                
             expect(rejectEmail).toBe(true);
        });

问题是当拒绝承诺时,catch 永远不会执行。我相信这是我对承诺的误解。

有什么想法吗为什么 catch 和 then 在这里不起作用?

你在嘲笑 serviceApiEmail.send 方法吗?你真的到了那个时候吗?我会检查其他东西然后 rejectEmail 布尔值,因为使用 Javascript 你的测试将是错误的,即使 'then' 部分没有达到,所以你甚至可能没有达到 promise resolve 部分

如果在使用 $q.when()apiKey 不存在,则您正在解决承诺。这将表明一个成功完成的承诺。要指示失败,您应该使用 $q.reject

if(!apiKey) {
    return $q.reject("apiKey not present.");
}

此外,对于要在测试中执行的 thencatch 回调,您通常需要触发摘要循环。这样做的通常方法是测试是获取对 $rootScope 的引用并调用 $rootScope.$digest().