茉莉花的回报在一家被嘲笑的工厂的承诺中被拒绝

Jasmine return rejected in a mocked factory's promise

本文关键字:工厂 承诺 拒绝 一家 茉莉花 回报      更新时间:2023-09-26

我的控制器的初始化:

    var init = function () {
        httpUsers.getUsers().then(function (data) {
            $timeout(function() {
                // Do something...
            });
        }).catch(function (error) {
            vm.error = "Me!";
            toastr.error(error);
        });
    }

我的模拟服务:

beforeEach(function() {
    module('httpService', function($provide) {
        $provide.factory('httpUsers', function () {
            var service = {
                getUsers: getUsers
            }
            function getUsers() {
                    deferred = $q.defer(); // deferred is a global variable
                    deferred.resolve([
                        { id: 1, firstName: "John", lastName: "Doe" },
                        { id: 2, firstName: "Jane", lastName: "Doe" },
                        { id: 3, firstName: "Jack", lastName: "Doe" }
                    ]);
                    return deferred.promise;
            };
            return service;
        });
    });
});

一切正常,可以返回已解决的承诺。

但是,我想在控制器的 init 函数中测试 catch 子句。

我试过这个:

describe('init', function() {
    it('should throw error', function () {
        deferred.reject('testing');
        expect(controller.error).toBe("Error!");  // NOTE: 'vm' is set to 'this', so controller is 'vm'
    });
});

但我得到的只是:

Expected undefined to be 'Error!'.

我没有收到"测试","我!"或"错误! 如何强制拒绝测试中的承诺?

谢谢!

编辑
这是我的控制器注入:

beforeEach(inject(function(_$controller_, _$rootScope_, _$q_, _$timeout_, _global_) {
    $rootScope = _$rootScope_;
    $scope = _$rootScope_.$new();
    $q = _$q_;
    $timeout = _$timeout_;
    global = _global_;
    controller = _$controller_('usersController', {
        $rootScope: $rootScope,
        $scope: $scope,
        $q: $q
    });
    $timeout.flush();
}));
如下所示

: -您的模拟服务

beforeEach(function() {
    module('httpService', function($provide) {
        $provide.factory('httpUsers', function () {
            var service = {
                getUsers: getUsers
            }
            function getUsers() {
                deferred = $q.defer(); // deferred is a global variable
                return deferred.promise;
            };
            return service;
        });
    });
});

您的拒绝测试

describe('init', function() {
    it('should throw error', function () {
        deferred.reject('testing');
        $scope.$apply();
        expect(controller.error).toBe("Error!"); 
    });
});

您的解析测试

describe('init', function() {
    it('should throw error', function () {
        deferred.resolve([
                    { id: 1, firstName: "John", lastName: "Doe" },
                    { id: 2, firstName: "Jane", lastName: "Doe" },
                    { id: 3, firstName: "Jack", lastName: "Doe" }
                ]);
        $scope.$apply();
        $timeout.flush();
        expect(controller.error).toBe("Error!"); 
    });
});