编辑:本质上,我正在寻找执行无后端开发和测试的最佳实践。
我希望能够独立于我的 Angular 应用程序的其余部分来手动排除故障/调试已编译的指令。我一直在尝试将 jasmine 与 karma runner 一起使用来实现这一目标,但收效甚微。
根据我的示例指令,我编写了一个测试来编译指令并将其添加到托管页面的正文元素中。该元素出现了,但是当我尝试与其交互时,例如使用绑定(bind)到指令事件处理程序的 ng-click 单击一个元素,“clickme”事件处理程序将不会被执行。但是,如果我在测试范围内以编程方式单击元素,事件处理程序将按预期执行。
指令:
angular.module('myModule', [])
.directive('foo', function() {
return {
restrict: 'E',
template: '<div id="bar" style="width:100px;height:100px;background-color:black;" ng-click="clickme()"></div>',
scope: {},
link: function(scope) {
scope.clickme = function() {
console.log('clickme called');
};
}
};
});
测试
describe('myDirective', function() {
var $compile = null, $rootScope = null, element = null, scope = null;
beforeEach(module('myModule'));
beforeEach(inject(['$compile', '$rootScope', function($c, $r) {
$compile = $c;
$rootScope = $r;
}]));
it("should", function(){
scope = $rootScope.$new();
element = angular.element('<foo></foo>');
$compile(element)(scope);
// Digest the scope to trigger a scope update and attach our directive's link function
scope.$digest();
// add the element to the page so I can see it and interact with it
$('body').append(element);
$('#bar', element).click();
expect(1).toBe(1);
});
});
如果您知道为什么我的事件处理程序在测试完成后无法存活,请告诉我!
我意识到我可能正在做一些 jasmine 或 angular 可能不适合做的事情。如果有人对我如何实现单独手动测试指令的目标有任何建议,那么我很想听听替代方案。
编辑:我从来没有弄清楚这个问题,但就无后端开发而言,我使用带有 grunt-express 的 Grunt 取得了很多成功。模块。然后我用了 grunt-connect-proxy将到我的 API(托管在/api 上)的连接代理到在不同端口上运行的快速服务器。它具有处理 CORS header 的选项。该解决方案使我能够启动一个简单的 express.js 服务器实现,我可以使用它来轻松模拟真实服务器的端点。
最佳答案
如果您使用的是 Grunt,这可能会有所帮助:https://github.com/ekonijn/grunt-require-demo/blob/master/doc/debugging-jasmine.md
否则,普通的老式 PhantomJS 调试也有帮助:https://github.com/ariya/phantomjs/wiki/Troubleshooting#remote-debugging
关于javascript - 使用 Jasmine (无后端测试)单独手动调试 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21149798/