在茉莉测试不叫AngularJS指令链接功能 [英] AngularJS directive link function not called in jasmine test
问题描述
我要创建一个调用在其链接服务的元素指令
功能:
I'm creating an element directive that calls a service in its link
function:
app.directive('depositList', ['depositService', function (depositService) {
return {
templateUrl: 'depositList.html',
restrict: 'E',
scope: {
status: '@status',
title: '@title'
},
link: function (scope) {
scope.depositsInfo = depositService.getDeposits({
status: scope.status
});
}
};
}]);
该服务是微不足道现在:
The service is trivial for now:
app.factory('depositService', function(){
return {
getDeposits: function(criteria){
return 'you searched for : ' + criteria.status;
}
};
});
我想写一个测试,确保 depositService.getDeposits()
时调用正确的状态值。
describe('Testing the directive', function() {
beforeEach(module('plunker'));
it('should query for pending deposits', inject(function ($rootScope, $compile, $httpBackend, depositService) {
spyOn(depositService, 'getDeposits').and.callFake(function(criteria){
return 'blah';
});
$httpBackend.when('GET', 'depositList.html')
.respond('<div></div>');
var elementString = '<deposit-list status="pending" title="blah"></deposit-list>';
var element = angular.element(elementString);
var scope = $rootScope.$new();
$compile(element)(scope);
scope.$digest();
var times = depositService.getDeposits.calls.all().length;
expect(times).toBe(1);
}));
});
由于次=== 0,这code运行在浏览器中细测试失败,但在测试中的链接
功能和服务似乎永远叫做。有什么想法?
The test fails because times === 0. This code runs fine in the browser, but in the test the link
function and the service never seem to be called. Any thoughts?
plunker: http://plnkr.co/edit/69jK8c
推荐答案
您不翼而飞 $ httpBackend.flush()
,它告诉模拟 $ httpBackend
返回一个模板。模板是从来没有加载,所以该指令链接功能没有什么来链接。
You were missing $httpBackend.flush()
, which tells the mock $httpBackend
to return a template. The template was never loading, so the directive link function had nothing to link against.
固定plunker: http://plnkr.co/edit/ylgRrz?p=$p$pview
Fixed plunker: http://plnkr.co/edit/ylgRrz?p=preview
code:
describe('Testing the directive', function() {
beforeEach(module('plunker'));
it('should query for pending deposits', inject(function ($rootScope, $compile, $httpBackend, depositService) {
spyOn(depositService, 'getDeposits').and.callFake(function(criteria){
return 'blah';
});
$httpBackend.when('GET', 'depositList.html')
.respond('<div></div>');
var elementString = '<deposit-list status="pending" title="blah"></deposit-list>';
var element = angular.element(elementString);
var scope = $rootScope.$new();
$compile(element)(scope);
scope.$digest();
$httpBackend.flush();
var times = depositService.getDeposits.calls.all().length;
expect(times).toBe(1);
}));
});
这篇关于在茉莉测试不叫AngularJS指令链接功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!