使用jasmine手动调试角度指令(无后端测试)

时间:2014-01-15 22:40:30

标签: javascript angularjs jasmine karma-runner

编辑:基本上我正在寻找执行无后端开发的最佳实践&测试

我希望能够独立于我的角度应用程序的其余部分手动排除故障/调试已编译的指令。我一直试图用茉莉花与业力跑步者来实现这一目标,但收效甚微。

根据我的示例指令,我编写了一个测试,它将编译该指令并将其添加到托管页面的body元素中。元素显示,但是当我尝试与它进行交互时,例如单击一个绑定到指令事件处理程序的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);
    });
});

如果您对测试完成后我的事件处理程序无法存活的原因有所了解,请告诉我们!

我意识到我可能正在做一些茉莉花或棱角分明的东西。如果有人对我如何实现单独手动测试指令的目标有任何建议,那么我很乐意听到替代方案。

编辑:我从来没有想过这个问题,但就无后端开发而言,我使用Grunt和grunt-express模块取得了很大的成功。然后我使用grunt-connect-proxy代理连接到我的API(托管在/ api上)到运行在不同端口上的快速服务器。它有处理CORS头的选项。这个解决方案允许我启动一个简单的express.js服务器实现,我可以用它来轻松地模拟我真实服务器的端点。

1 个答案:

答案 0 :(得分:0)

如果你正在使用Grunt,这可能会有所帮助:https://github.com/ekonijn/grunt-require-demo/blob/master/doc/debugging-jasmine.md

否则,普通的PhantomJS调试也可以提供帮助:https://github.com/ariya/phantomjs/wiki/Troubleshooting#remote-debugging