【问题标题】:Unit testing in AngularJS with mock $resource使用模拟 $resource 在 AngularJS 中进行单元测试
【发布时间】:2013-06-13 10:16:44
【问题描述】:

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

app.js

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

controller.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;
    });
});

services.js

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

controllerSpec.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);
        }));
    });
});

【问题讨论】:

  • 我遇到了同样的错误。我正在为控制器编写测试。这是在它自己的文件中。所以我将控制器脚本包含在测试 jasmine 测试页面中,那么我是否需要 app.js 也包含在其中以向我的控制器编写测试?您能否还包括您包含的用于编写测试的脚本

标签: javascript angularjs unit-testing jasmine karma-runner


【解决方案1】:

最终使用了这个例子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();
    }));
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2014-02-08
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多