【问题标题】:Invoking service method in Jasmine在 Jasmine 中调用服务方法
【发布时间】:2015-04-28 08:16:12
【问题描述】:

使用 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();
    });
});

据我了解 with 注入器,我应该能够使用注入的服务。没有 (1a-1d) 我得到一个错误:

错误:[$injector:unpr] 未知提供者:RoomParamsSvcProvider

但是现在它也不起作用了。我收到一个错误,表示 test() 不是函数:

jasmine typeerror 'undefined' 不是函数(评估 'RoomsParamsSvc.test()')

我的服务是这样的:

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

你有什么建议吗?

【问题讨论】:

    标签: javascript angularjs jasmine karma-jasmine


    【解决方案1】:

    第 1a-1d 行不是必需的,因为“RoomsParamsSvc”已加载到“房间”模块中。但是您引用了未定义的 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

    【讨论】:

    • 感谢您的回答。不幸的是,当我将引用 'RoomsController' 更改为您所写的 function() {} 时......什么都没有改变。通过删除第 1a-1d 行并在 beforeEach(module('rooms')) 之前写入,我仍然得到问题中第一个提到的错误
    • 你使用最新的库吗?查看示例 - 它可以工作 - 并将其与您的代码进行比较。或者自己提供一个工作的 plunker。
    • 迈克尔 - 谢谢,它有帮助。我只是在该控制器中有一些其他服务的附加代码,我一开始没有添加,我正在使用 $provide.value 与它们。但是,即使不添加所有依赖服务,我仍然只能测试上面的一项服务 (RoomParamsSvc)。现在我意识到了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2021-07-01
    • 2012-08-10
    • 1970-01-01
    相关资源
    最近更新 更多