2014-04-14 6 views
1

간단히 말해서, 서비스에서 범위에 설정된 속성을 가진 컨트롤러가 있습니다.각도 서비스에서 데이터를 가져 오는 각도로 컨트롤러를 테스트하는 방법은 무엇입니까?

컨트롤러 :

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

, 어떻게 내가이 컨트롤러를 테스트합니까? (참고로,이 서비스는 내 사양하는 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"); 
      }); 
     }); 
    }); 
}); 
+0

당신의 컨트롤러를 만들었습니다. – aet

+0

고마워요. 그게 내가 생각하고있는 것입니다. 서비스를 조롱하고 재 스민에서 사용하는 스 니펫을 가지고 있습니까? – mariocatch

+0

결국 여러 가지 기법을 사용하여 답변을 얻었습니다. 내가 제공 한 것은 단지 하나의 방법 일 뿐이다. smine spyOn 너무, 그리고 조롱 노력이 얼마나 복잡 하느냐에 따라, 그것은 더 쉬울지도 모른다. – aet

답변

1

아마 이런 식으로 뭔가 : 당신은 당신의 automationService을 조롱에 모의를 주입한다

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"); 
      }); 
     }); 
    }); 
}); 
관련 문제