简体   繁体   English

在茉莉花中测试拒绝的承诺

[英]Testing rejected promise in Jasmine

I am building AngularJS application and I am trying to unit test it. 我正在构建AngularJS应用程序,并且正在尝试对其进行单元测试。 What I want to test is rejected scenario. 我要测试的是拒绝方案。

This is the service I am trying to test: 这是我要测试的服务:

.factory('LoginService',['Login', 'consoleService', function(Login, consoleService){
return {
    getActiveUser: function() {
        return Login.query({}).$promise.then(
            function (users) {
                return users[0];
            },
            function (error) {
                consoleService.print(error);
            }
        );
    }
};

}]); }]);

I am trying to write unit test for rejected scenario (error occurred). 我正在尝试为拒绝的方案(发生错误)编写单元测试。 And I want to be sure that print function is gonna be called when some error occurres. 而且我想确保在发生某些错误时将调用打印功能。 I tried different examples, but neither one didn´t work. 我尝试了不同的示例,但没有一个没有用。 Does anyone have idea what is correct way to test it? 有谁知道测试的正确方法是什么?

The Mock rejection service has already been discussed in the below link 模拟拒绝服务已在下面的链接中进行了讨论

How to use mock $httpBackend to test error branch 如何使用模拟$ httpBackend测试错误分支

You could mock the Login service, then depending on a variable have it call the pass or fail functions. 您可以模拟登录服务,然后根据变量将其称为通过或失败函数。

var failLogin;
beforeEach(module(function ($provide) {
    failLogin = false;        
    var mockLogin = {
        query: function(data) {
            return {
               $promise: {
                   then: function(pass, fail) {
                       if (failLogin) {
                           fail('failure data');
                       } else {
                           pass('pass data');
                       }
                   }
               }
            }
        } 
    } 

    $provide.value('login', mockLogin);
}

it('should pass', function(){
    LoginService.getActiveUser();
    // should pass
});


it('should fail', function(){
    failLogin = true;
    LoginService.getActiveUser();
    // should fail
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM