AngularJS-指令单元不测试任何内容

AngularJS - directive unit test nothing

本文关键字:任何内 测试 指令 单元 AngularJS-      更新时间:2023-09-26

我正在尝试SIMPLE指令的单元测试,但它不起作用。我得到:Error: Unexpected request: GET my-directive.html No more request expected

不知道这意味着什么,它在网页上有效。。。

现场演示:http://plnkr.co/edit/SrtwW21qcfUAM7mEj4A5?p=preview

方向性Spec.js

describe('Directive: myDirective', function() {
  beforeEach(module('myDirectiveModule'));
  var element;
  var scope;
  beforeEach(inject(function($rootScope, $compile) {
    scope = $rootScope.$new();
    element = angular.element('<my-directive something="thing"></my-directive>');
    element = $compile(element)(scope);
    scope.thing = {name: 'My thing'};
    scope.$digest();
  }));
   it('should update the rendered text when scope changes', function() {
    scope.thing.name = 'My new thing';
    scope.$digest();
    var h1 = element.find('h1');
    expect(h1.text()).toBe('My new thing');
  });
});

app.js

angular.module('myDirectiveModule', [])
  .directive('myDirective', function() {
    return {
      bindToController: true,
      controller: function() {
        var vm = this;
        vm.doSomething = doSomething;
        function doSomething() {
          vm.something.name = 'Do something';
        }
      },
      controllerAs: 'vm',
      restrict: 'E',
      scope: {
        something: '='
      },
      templateUrl: 'my-directive.html'
    };
  })
  .controller('DirCtrl', ['$scope', function() {
    this.getName = 'Hello world!';
  }]);

如何简单地测试指令单元测试?

您需要模拟模板请求。因为该指令具有templateUrl,所以它尝试发出get请求,但$http不期望有任何请求,因此它失败了。您可以用自己的响应模拟请求,或者将模板放入模板缓存服务中。

  beforeEach(inject(function($rootScope, $compile, $templateCache) {
    $templateCache.put('my-directive.html','<h1 ng-click="vm.doSomething()">{{vm.something.name}}</h1>');
    scope = $rootScope.$new();
    element = angular.element('<my-directive something="thing"></my-directive>');
    element = $compile(element)(scope);
    scope.thing = {name: 'My thing'};
    scope.$digest();
  }));

另外,在it函数上,调用$apply并使用$evalAsync。看看我的叉子。

相关文章: