我们如何模拟我们的服务来测试控制器?

时间:2014-10-13 07:17:29

标签: javascript angularjs testing

我是角度js的新手并尝试测试控制器。

我有这样的服务:

angular.module('test'){

        service.getAllServices = function()
        {
            var fullPath = url
            var deferred = $q.defer()

            if(!$.isEmptyObject(service.allServices))
                deferred.resolve(service.allServices)
            else
                $http.get(fullPath)
                    .success(function(data,status,headers,config){
                        service.allServices = data
                        deferred.resolve(service.allServices)
                    })
                    .error(deferred.object)

            return deferred.promise;
        }


    })

控制器看起来像这样:

angular.module('test')
  .controller('MainCtrl', function ($scope,$http,HttpService) {
    $scope.awesomeThings = [
        "Loading"
    ];


    $scope.loadServices = function()
    {
        HttpService.getAllServices().then(function(result){
//            console.log("Success")
            $scope.awesomeThings = result.entities
        },function(reason){
            console.log(reason)
        })
    };

我有一个这样的测试用例:

describe('Testing controller', function () {

    // load the controller's module
    beforeEach(module('test'));

    var MainCtrl,
        scope;

    // Initialize the controller and a mock scope
    beforeEach(inject(function ($controller, $rootScope,$q,HttpService) {
        scope = $rootScope.$new();

        var deferred = $q.defer();
        var response = {
            things: 'and stuff'
        }

        deferred.resolve(response);
        spyOn(HttpService, 'getAllServices').andReturn(deferred.promise);

        MainCtrl = $controller('MainCtrl', {
            $scope: scope,
            HttpService : HttpService
        });

        scope.loadServices();
    }));


    it('Controller is dummy, just gives back, what services gives back', function () {
        expect(scope.awesomeThings).toEqual({
            things: 'and stuff'
        });
    });


});

即使我正在注入deferred对象,看起来我的测试用例仍然失败,并显示以下消息:

Expected [ 'Loading' ] to equal { things : 'and stuff' }.

我犯错误的地方?

1 个答案:

答案 0 :(得分:0)

您需要调用摘要来强制执行promise成功函数。您可以在测试中或在调用loadServices之后的设置中执行此操作,如下所示:

scope.loadServices();
scope.$digest();

希望这有帮助。