如何單元測試這條使$ http調用出去的指令爲MyService
?我如何正確模擬或偵察MyService
?單元測試使用注入服務的角度指令
angular.module('example')
.directive('myDirective', ['MyService', function(MyService) {
return {
restrict: 'E',
replace: true,
templateUrl: 'templates/myDirective.html',
scope: {
name: '@',
required: '='
},
link: function(scope, el, attrs, billingCtrl) {
scope.data = [];
MyService.get()
.then(function(res) {
scope.data = res;
});
}
};
}]);
我的測試:
describe('Directive: <my-directive>', function() {
// setup code
beforeEach(module('example'));
var element;
var compile;
var scope;
var compiledElementScope;
var validTemplate = '<my-directive ng-model="testModel" name="test"></my-directive>';
var MyService = { get: function() {} };
var $q;
function getCompiledElement(template) {
var compiledElement;
compiledElement = compile(template || validTemplate)(scope);
scope.$digest();
return compiledElement;
}
beforeEach(function() {
module(function($provide) {
$provide.value('MyService', MyService);
});
inject(function($compile, $rootScope, _$q_) {
compile = $compile;
scope = $rootScope.$new();
$q = _$q_;
});
});
describe('my directive', function() {
var element;
beforeEach(function() {
element = getCompiledElement(validTemplate);
});
it('should make a call to MyService and update scope.data', function() {
// how do I asset the following
expect(scope.data).toEqual(...);
});
})
});