简体   繁体   中英

AngularJS - directive unit test nothing

I am trying a SIMPLE directive Unit Test but it is not working. I am getting: Error: Unexpected request: GET my-directive.html No more request expected

Not sure what that means, it works in the web page...

LIVE DEMO: 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!';
  }]);

How do I simply test a directive unit test?

You need to mock the template request. Because the directive has the templateUrl it try to make a get request, but the $http doesn't expect any request so it fails. You can mock the request with a response of yours or put the template into the template cache service.

  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();
  }));

Also on your it function call $apply and use $evalAsync . See my forked plunker.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM