[英]How to properly unit test Angular directive
我正在嘗試測試Angular指令,但始終遇到以下錯誤:
Error: Unexpected request: GET /api/players/info
我相信這是因為在指令定義對象中對控制器的引用,但是我不確定如何處理它。 以下是我的指令,然后是我的測試:
playerInfo.directive.js:
'use strict';
angular.module('gameApp')
.directive('playerInfo', playerInfo);
function playerInfo() {
var directive = {
link: link,
restrict: 'E',
templateUrl: '/app/player/playerInfo.directive.html',
controller: 'PlayerInfoController',
controllerAs: 'playerInfo'
};
return directive;
function link(scope, element) {
var address = angular.element(element[0].getElementsByClassName('blur'));
address.on('click', function() {
address.css({'-webkit-filter': 'none'});
});
}
}
playerInfoSpec.js:
'use strict';
describe('playerInfo directive', function() {
var element;
var scope;
beforeEach(module('gameApp'));
beforeEach(inject(function($templateCache) {
var templateUrl = '/app/player/playerInfo.directive.html';
var asynchronous = false;
var req = new XMLHttpRequest();
req.onload = function() {
$templateCache.put(templateUrl, this.responseText);
};
req.open('get', '/base' + templateUrl, asynchronous);
req.send();
}));
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
element = '<player-info></player-info>';
element = $compile(element)(scope);
}));
it('should replace the element with the appropriate content', function() {
scope.$digest();
expect(element.html()).toContain("Score:");
});
});
我的控制器使用注入的服務將GET
請求發送到/api/players/info
,這就是為什么我認為此錯誤與我的指令定義對象中的控制器引用有關的原因。
您的控制器正在對/ api / players / info進行遠程調用。 在進行單元測試時(我猜您正在使用Karma和Jasmine),您將不得不使用ngMock模塊和$ httpBackend服務來模擬遠程調用。
'use strict';
describe('playerInfo directive', function() {
var element;
var scope;
var $httpBackend
beforeEach(module('gameApp'));
beforeEach(inject(function($templateCache) {
var templateUrl = '/app/player/playerInfo.directive.html';
var asynchronous = false;
var req = new XMLHttpRequest();
req.onload = function() {
$templateCache.put(templateUrl, this.responseText);
};
req.open('get', '/base' + templateUrl, asynchronous);
req.send();
}));
beforeEach(inject(function($rootScope, $compile, _$httpBackend_) {
scope = $rootScope.$new();
element = '<player-info></player-info>';
element = $compile(element)(scope);
$httpBackend = _$httpBackend_;
$httpBackend.whenGET('/api/players/info').respond(200, '');
}));
it('should replace the element with the appropriate content', function() {
scope.$digest();
expect(element.html()).toContain("Score:");
$httpBackend.flush()
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.