我有一个查看当前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);
}
};
});
更新:
这是我尝试的一项测试,基于以下的初步回复:
描述(&#39;我的指令测试&#39;,function(){ var $ scope,compile,element,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
答案 0 :(得分:0)
您可以使用$provide
var 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;
})
}));
然后按照有关如何对测试指令进行单元化的角度文档的instructions进行操作。
答案 1 :(得分:0)
使用Jasmine模拟进行单元测试。 下载库后:
describe('mydirective', function(){
var $location, myService;
beforeEach(module('myApp'));
beforeEach(inject(function (_myService_, _$location_) {
myService = _myService_;
$location = _$location_;
spyOn(myService, "getCustID").and.returnValue("123462");
}));
//Write stuff for your directive here
it('should have made a call to ', function(){
expect(myService.getCustId).toHaveBeenCalled()
});
以获取更多参考:http://volaresystems.com/blog/post/2014/12/10/Mocking-calls-with-Jasmine