在Jasmine中调用服务方法

时间:2015-04-28 08:16:12

标签: javascript angularjs jasmine karma-jasmine

使用Angular和Jasmine我想用一些模型数据运行服务方法。下面是我的测试代码,它使用一些工作的RoomsController尝试在RoomsParamsSvc上运行test()方法:

describe('Rooms Controller', function() { 
    var RoomsController,
        scope,
        location,
        httpBackend,
        RoomsParamsSvc;    
    beforeEach(module('rooms', function ($provide, $injector) {                    
        RoomsParamsSvc = function () { //(1a)
            return $injector.get('RoomsParamsSvc'); //(1b)
        };         //(1c)
        $provide.value('RoomsParamsSvc', RoomsParamsSvc);   //(1d)
    }));
    beforeEach(inject(function($controller, $rootScope, $location, $httpBackend, _RoomsParamsSvc_) {
            // Set a new global scope
            scope = $rootScope.$new();
            location = $location;
            httpBackend = $httpBackend;
            RoomsParamsSvc = _RoomsParamsSvc_;
            RoomsController = $controller('RoomsController', {
                $scope: scope,
                $location: location,
                RoomsParamsSvc: RoomsParamsSvc
            });
        }));
    it('should have test as a function', function () {       
        var t = RoomsParamsSvc.test();
    });
});

据我所知,使用带喷射器我应该可以使用该注入服务。没有(1a-1d)我收到了一个错误:

  

错误:[$ injector:unpr]未知提供商:RoomsParamsSvcProvider< -   RoomsParamsSvc

然而现在它也不起作用。我得到一个错误意味着test()不是函数:

  

jasmine typeerror' undefined'不是一个功能(评估' RoomsParamsSvc.test()')

我的服务如下:

var roomsApp = angular.module('rooms', []);
roomsApp.factory('RoomsParamsSvc', function () {
    var factory = {};    
    factory.test = function ()
    {
        return '';
    }
    return factory;
});

你有什么建议吗?

1 个答案:

答案 0 :(得分:0)

不需要第1a-1d行,因为'RoomsParamsSvc'已加载到您的'room'模块中。但是你引用了RoomsController,这是未定义的。

beforeEach(module('rooms'));
beforeEach(inject(function($controller, $rootScope, $location, $httpBackend, _RoomsParamsSvc_) {
        // Set a new global scope
        scope = $rootScope.$new();
        location = $location;
        httpBackend = $httpBackend;
        RoomsParamsSvc = _RoomsParamsSvc_;
        RoomsController = $controller(function() {}, {
            $scope: scope,
            $location: location,
            RoomsParamsSvc: RoomsParamsSvc
        });
        console.log(RoomsParamsSvc);
    }));

Plunker