带有外部依赖项的Jasmine单元测试指令失败,类型错误:'[object对象]'

Jasmine unit testing directives with external dependencies fails with TypeError: '[object Object]'

本文关键字:错误 对象 object 类型 依赖 外部 Jasmine 失败 指令 单元测试      更新时间:2023-09-26

我运行规范时收到一个错误。我正在测试一个包含此服务的指令。测试返回错误消息:

TypeError:"[object object]"不是函数(正在计算"angular("RecursionHelper")")。

不确定我错过了什么才能让它发挥作用。我使用的是Angular 1.3&Jasmine 2.0。

我的指令:

return RecursionHelper.compile(element, function (scope, Element, Attrs,     contro, transFn) {
   //directive functions
});

我的规格:

   beforeEach(function () {
       angular('RecursionHelper');
   });
  element = angular.element('<directive></directive>');
            $scope.directiveList = directiveList;
            RecursionHelper.compile(element)($scope);
            $scope.$digest();

beforeEach块中,您应该加载包含指令的应用程序模块。更改:

beforeEach(function () {
    angular('RecursionHelper');
});

收件人:

beforeEach(function () {
    module('MyApp'); //change to your application name. 
});

此外,您应该在每次jasmine测试之前注入$compile服务和$rootScope。您正在使用compile服务在不注入指令的情况下呈现指令。

只需添加到您的beforeEach:

inject(function($compile, $rootScope, $injector) {
    compile = $compile;
    $scope = $rootScope.$new();
});

最终代码应该看起来像:

   beforeEach(function () {
       module('MyApp'); //change to your application name.
       inject(function($compile, $rootScope, $injector) {
           compile = $compile;
           $scope = $rootScope.$new();
       }); 
   });    

it('make an assertion', function() {
    var element = angular.element('<directive></directive>');
    $scope.directiveList = directiveList;
    compiledElement = compile(element)($scope);
    $scope.$digest();
});