如何以角度测试控制器,从角度服务获取数据?

时间:2014-04-14 18:16:09

标签: javascript angularjs jasmine

非常简单,我有一个控制器,它在服务范围内设置了属性。

控制器:

dadApp.controller('landingController', function($scope, automationService) {
    $scope.hello = "from controller";
    $scope.foo = automationService.foo;

    // load data from service.
});

服务:

dadApp.factory('automationService', function($http) {
    var _foo = [];

    $http.get('/api/automation')
        .then(function(result) {
                angular.copy(result.data, _foo);
            },
            function() {
                alert('error');
            });

    return {
        foo: _foo
    };
});

在我的specs / test文件中,如何测试此控制器,因为它取决于服务? (仅供参考,该服务是ASP.NET WebAPI 2。

这是我的规格:

/// <reference path="../Scripts/angular.js" />
/// <reference path="../Scripts/angular-mocks.js" />
/// <reference path="../Scripts/angular-resource.js" />
/// <reference path="../Scripts/angular-route.js" />
/// <reference path="../app/app.js" />
/// <reference path="../app/services/automationService.js" />
/// <reference path="../app/controllers/landingController.js" />
'use strict';

var scope, ctrl;

describe('DAD tests', function() {
    beforeEach(module('dadApp'));

    beforeEach(inject(function($controller, $rootScope) {
        scope = $rootScope.$new();
        ctrl = $controller('landingController', { $scope: scope });
    }));

    describe('landing controller tests', function() {
        describe('scope.hello', function() {
            it('should equal "from controller"', function() {
                expect(scope.hello).toEqual("from controller");
            });
        });
    });
});

1 个答案:

答案 0 :(得分:1)

也许是这样的:

var mockedFoo = {
    bar: true,
    baz: 123,
    other: "string"
};
var automationServiceMock = {
    foo: function() {
        return mockedFoo;
    }
};
describe('DAD tests', function() {
    beforeEach(module('dadApp'));

    beforeEach(inject(function($controller, $rootScope) {
        scope = $rootScope.$new();
        ctrl = $controller('landingController', {
            $scope: scope, 
            automationService: automationServiceMock 
        });
    }));

    describe('landing controller tests', function() {
        describe('scope.hello', function() {
            it('should equal "from controller"', function() {
                expect(scope.hello).toEqual("from controller");
            });
        });
    });
});