Jasmine:从 Angular Material 嘲笑 $animate

Jasmine: mocking $animate from Angular Material

我正在尝试在 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 的正确模拟方法是什么?

根据你的 plunkr,有几个问题:

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

    <html ng-app="splashDirective">
    
  2. 您的测试尝试从 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);
    });
    

这是你的 plunkr fixed version