3

试图在 AngularJS 中进行一些单元测试(使用 jasmine 和业力)工作并努力理解依赖注入...业力中的当前错误消息显示为“错误:参数 'fn' 不是函数,得到字符串”

应用程序.js

angular.module('App', [ 'App.Services', 'App.Controllers', 'App.Directives']);

控制器.js

angular.module('App.Controllers', []).
controller('MarketplaceCtrl', function ($scope, apiCall) {
    apiCall.query({
        type: 'engagement',
        engagement_status__in: '0,1'
    }, function(data) {
        var engagements = {};
        $.each(data.objects, function (i, engagement) {
           engagements[engagement.lawyer_id] = engagement
        });
        $scope.engagements = engagements;
    });
});

服务.js

angular.module('App.Services', ['ngResource']).
factory('apiCall', function ($resource) {
    return $resource('/api/v1/:type',
        {type: '@type'},
        {
            query: {
                method: 'GET',
                isArray: false
            }
        }
    );
});

控制器规范.js

describe('controllers', function () {

    beforeEach(
        module('App', ['App.Controllers', 'App.Directives', 'App.Services'])
    );

    describe('MarketplaceCtrl', function () {
        var scope, ctrl, $httpBackend;

        beforeEach(inject(function (_$httpBackend_, $rootScope, $controller) {
            $httpBackend = _$httpBackend_;
            $httpBackend.expectGET('/api/v1/engagement?engagement_status__in=0,1').
                respond([]);
            scope = $rootScope.$new();
            /* Why is MarketplaceCtrl not working? :( */
            ctrl = $controller('MarketplaceCtrl', {$scope: scope});
        }));

        it('should have a MarketplaceCtrl controller', (function () {
            expect(ctrl).not.to.equal(null);
        }));
    });
});
4

1 回答 1

3

最终使用了这个例子https://github.com/tebriel/angular-seed/commit/b653ce8e642ebd3e2978d5404db81897edc88bcb#commitcomment-3416223

基本上:

describe('controllers', function(){
    beforeEach(module('myApp.controllers'));

    it('should ....', inject(function($controller) {
        //spec body
        var myCtrl1 = $controller('MyCtrl1');
        expect(myCtrl1).toBeDefined();
    }));

    it('should ....', inject(function($controller) {
        //spec body
        var myCtrl2 = $controller('MyCtrl2');
        expect(myCtrl2).toBeDefined();
    }));
});
于 2013-06-13T13:21:07.697 回答