我有着眼于当前的URL和检索查询字符串参数的服务:单元测试调用的服务的指令
app.service('myService', function($location) {
return {
getCustID : function() {
return $location.search().custID;
}
};
});
而且我已经能够成功的单元测试通过:
describe('myService', function(){
var $location, myService;
beforeEach(module('myApp'));
beforeEach(inject(function (_myService_, _$location_) {
this.myService = _myService_;
$location = _$location_;
}));
it('should get a promoCode from the url', function(){
$location.url('/?custID=DSGAG444355');
expect(this.myService.getCustID()).toEqual('DSGAG444355');
});
});
但是,我有一个使用上述服务的指令。我如何测试?
指令:
app.directive('imageDirective', function($compile, myService) {
return {
restrict: 'A',
replace: true,
scope: true,
link: function (scope, element, attrs) {
var custID = myService.getCustID();
var myText;
if (custID == 3) {
text = 'cust ID is 3';
}
var jqLiteWrappedElement = angular.element('<img src="/resources/img/welcome.png' alt=" ' + myText + '" />');
element.replaceWith(jqLiteWrappedElement);
$compile(jqLiteWrappedElement)(scope);
}
};
});
UPDATE:
这是一个测试我基于以下INTIAL repsonse尝试:
描述( '我的指令测试',函数(){ 变量$范围,编译,元素,myMock;
beforeEach(module('myApp'));
beforeEach(module(function($provide){
myMock = {}//Mock the service using jasmine.spyObj, or however you want
$provide.factory('myService', function(){
return myMock;
})
}));
beforeEach(inject(function ($rootScope, $compile) {
$scope = $rootScope.$new();
element = angular.element("<img my-directive/>");
$compile(element)($scope);
$scope.$digest();
}));
it('should get a parameter from the URL', function(){
$location.url('/?custID=003');
expect(myMock.getcustID()).toEqual('003');
});
});
TypeError: myService.getCustID is not a function
感谢。请参阅上述更新。 –
@OamPsy你的模拟没有设置功能。你需要指定你想要的模拟函数,这可能是真实服务所有的函数:'myMock = jasmine.createSpyObj('myServiceMock',['getCustID',/ *等所有函数你想嘲笑* /])' – Gustav
你可以请创建一个蹲点? –