AngularJS - 指令单元测试没什么

时间:2015-12-09 07:36:31

标签: javascript angularjs unit-testing

我正在尝试SIMPLE指令单元测试,但它无法正常工作。我得到了:Error: Unexpected request: GET my-directive.html No more request expected

不确定这意味着什么,它可以在网页上运行......

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

directiveSpec.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!';
  }]);

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

1 个答案:

答案 0 :(得分:1)

您需要模拟模板请求。因为该指令具有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上并使用$evalAsyncSee my forked plunker.

相关问题