gpt4 book ai didi

javascript - 如何正确地对 Angular 指令进行单元测试

转载 作者:行者123 更新时间:2023-11-30 16:45:44 24 4
gpt4 key购买 nike

我正在尝试测试 Angular 指令,但一直遇到以下错误:

Error: Unexpected request: GET /api/players/info

我相信这是因为在我的指令定义对象中引用了我的 Controller ,但我不确定如何处理它。下面是我的指令,然后是我的测试:

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

我的 Controller 使用注入(inject)服务向 /api/players/info 发送 GET 请求,这就是为什么我认为此错误与我的 Controller 引用有关在我的指令定义对象中。

最佳答案

您的 Controller 正在远程调用/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()
});
});

有完整的文档 here
关于underscores

关于javascript - 如何正确地对 Angular 指令进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31267507/

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