从从控制器调用的服务调用的服务中获取未定义

时间:2016-06-06 13:15:52

标签: angularjs mocking jasmine karma-runner

在编写单元测试用例期间,我遇到了一个问题,其中一个服务正在调用另一个服务并获得" undefined"作为回应。我需要嘲笑那个" undefined"价值并且不知道如何做到这一点。要完全理解场景,请查看详细说明。

精化

服务" B "从Controller调用。服务" B "正在呼叫服务" A "包含一个返回undefined的函数。现在我需要在Service" A "中模拟未定义的值。坐在控制器里。在这方面的任何帮助将受到高度赞赏。

我尝试了以下实施:

(服务A是authenticationService)

beforeEach(inject(function ( $controller, $rootScope, $httpBackend ,authenticationService ) {
        authenticationService = {
            getCredential: function(){
                return {loggedInUser:{id:1}};
            }
        };
        $scope = $rootScope.$new();
        authenticationService = authenticationService;

        httpMock = $httpBackend;
        manageTestSuiteCtrl = $controller("manageTestSuiteCtrl", {
            $scope : $rootScope, $rootScope : $rootScope, authenticationService  = authenticationService 
        });
    }));

但它没有用。然后我在测试用例中尝试间谍阻止

spyOn(authenticationService, "getCredential").and.callFake(function() {
            return {loggedInUser:{id:1}};
        });

也没有帮助。任何帮助将非常感激,因为我已经为这个问题粉碎了我的头像现在一周

1 个答案:

答案 0 :(得分:0)

嗯,根据您提供的内容,我建议您不要嘲笑服务A的方法,而是模拟服务B的方法,然后又调用服务A的方法和返回值未定义。这是因为你无论如何都要关注返回的值。

以下是我如何复制您描述的方案:

模块,serviceA,serviceB和控制器

var app = angular.module('myApp', [])

app.service('serviceA', function(){
    return{
        methodName: function(){
            return 'something'
        }
    }
});

app.service('serviceB', function(serviceA){
    return{
        methodName: function(){
            return serviceA.methodName();
        }
    }
});

app.controller('myAppController', function($scope, serviceB){
    $scope.greeting = 'Hello World!';
    $scope.b = serviceB.methodName();
});

<强>测试

describe('controller: myAppController', function() {

    var myAppController, $controller, $rootScope, $httpBackend ,authenticationService, scope, serviceB;

    beforeEach(function(){
        module('myApp');
    });

    beforeEach(inject(function ($controller, $rootScope, _serviceB_) {
        scope = $rootScope.$new();
        serviceB = _serviceB_;

        spyOn(serviceB, 'methodName').and.callFake(function(){
            return undefined;
        });

        myAppController = $controller('myAppController', {
            $scope: scope,
            serviceB: _serviceB_
        });
    }));

    describe('initialization', function(){
        it('should initialize some variables', function(){
            expect(serviceB.methodName).toHaveBeenCalled();
            expect(scope.greeting).toEqual('Hello World!');
            expect(scope.b).not.toBeDefined();
            expect(scope.b).toBe(undefined);
        });
    });


});

请随时评论是否对您有所帮助。如果没有,请对您面临的问题发表评论,我会相应地更新答案。

希望这会对你有所帮助。