gpt4 book ai didi

javascript - Jasmine 测试中未调用 AngularJS 指令链接函数

转载 作者:数据小太阳 更新时间:2023-10-29 04:06:07 25 4
gpt4 key购买 nike

我正在创建一个在其 link 函数中调用服务的元素指令:

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

目前该服务很简单:

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

测试失败,因为 times === 0。此代码在浏览器中运行良好,但在测试中,link 函数和服务似乎从未被调用。有什么想法吗?

笨蛋:http://plnkr.co/edit/69jK8c

最佳答案

您缺少 $httpBackend.flush(),它告诉 mock $httpBackend 返回一个模板。模板从未加载,因此指令链接函数没有任何可链接的对象。

修复了 plunker:http://plnkr.co/edit/ylgRrz?p=preview

代码:

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

关于javascript - Jasmine 测试中未调用 AngularJS 指令链接函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24387564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com