Jasmine:从Angular Material嘲笑$ animate

时间:2015-05-09 20:56:33

标签: javascript angularjs unit-testing karma-jasmine

我试图在Jasmine单元测试中模拟$animate服务。我正在测试的指令如下:

angular
    .module('splashDirective', ['ngMaterial'])
    .directive('mAppLoading', ['$animate', function($animate) {

    var link = function(scope, element, attributes) {

        $animate.leave(element.children().eq(1)).then(
            function cleanupAfterAnimation() {
                element.remove();
                scope = element = attributes = null;
            }
        );

   };

   return ({
       link: link,
       restrict: "C"
   });
}]);

这是一个非常简单的只等待cleanUpAfterAnimation(),以便它从DOM树中删除它。

我正尝试使用以下代码使用Jasmine + Karma进行测试:

describe('Testing Splash directive', function () {

    var $rootScope, $scope, $q,
        $compile,
        $directive,
        $body = $("body"),
        mock__animate = {
            leave: function () {
                return $q.when();
            }
        },
        html =
        "<div class='m-app-loading' ng-animate-children>" +
        "   <div class='animated-container'>" +
        "       <div class='messaging'>" +
        "           <h2>Test</h2>" +
        "       </div>" +
        "   </div>" +
        "</div>";

    beforeEach(function () {

        module('splashDirective', function ($provide) {
            $provide.value('$animate', mock__animate);
        });

        inject(function ($injector) {

            $rootScope = $injector.get('$rootScope');
            $compile = $injector.get('$compile');
            $q = $injector.get('$q');

            $scope = $rootScope.$new();
            $directive = $compile(angular.element(html))($scope);

        });

        $body.append($directive);
        $rootScope.$digest();

    });

    it('should compile the directive', function () {
        var div_directive = $("div.m-app-loading");
        expect(div_directive.length).toBe(1);
    });
});

但是,测试失败,因为看起来编译HTML时出现了问题。

我有以下运行的plnkr,显示异常:example

我做错了什么?模拟$animate的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

根据你的傻瓜,有几个问题:

  1. 您的Plunkr会发错误b / c您的模块名称不匹配。 在您的HTML中,您执行ng-app="plunkr",但在您定义的代码中 模块名称为“splashDirective”。这些名字应该是 相同的:

    <html ng-app="splashDirective">
    
  2. 您的测试尝试从页面中获取<body>元素 beforeEach()功能。这不起作用(你得到了一个 空数组)。所以正在调用$body.append($directive) 什么都没有。如果您检索并填充,您的测试将通过 实际测试中的正文(在it()函数内):

    it('should compile the directive', function () {
        $body = $("body");
        $body.append($directive);
        var div_directive = $("div.m-app-loading");
        expect(div_directive.length).toBe(1);
    });
    
  3. 当您的单元测试向主体添加元素时,您会发现 的页面,他们将保留在页面上 其余的测试运行。这可能会影响其他测试。你应该用 运行每个测试后清除afterEach()

    afterEach(function() {
        // sorry this is just from memory, please verify the syntax
        body.remove($directive);
    });
    
  4. 这是你的傻瓜的fixed version