Unit testing directive with AngularJS + Jasmine

大兔子大兔子 提交于 2019-12-25 03:53:08

问题


I am a new to unit-testing with jasmine, so iI hope this makes sense and is correct enough to get an answer , I am trying to test an angularJS directive

here is my plunker : http://jsfiddle.net/ksqhmkqm/13

in my case i am unable to get the input (id="Montid") value in jasmine

here is my angualr code

app.directive("monthNext", function () {

  console.log('massif');
  return {
    restrict: 'A',
    link: function (scope, element) {
      element.on('input', function () {
        var todaysYear = new Date();
        var u = todaysYear.getFullYear() - 2;

        if (element.val().length == 4) {

          var nextElement = element.next().next().next().next().next().next().next();
          nextElement = angular.element(document.querySelectorAll('#Montid'));

          if (element.val() <= u) {

            console.log(element.children());
            //var nextElement = angular.element(document.body).find('[tab index = 6]')
            console.log(nextElement);
            //nextElement.focus();

            console.log(nextElement);
            nextElement.val("");
            nextElement[0].focus();
          } else {
            // alert(nextElement.val());             
            console.log(nextElement.val("01"));
          }
        }

      });
    }
  };
});

here is my jasmine code

describe('CommonBusInfo', function () {
  var element, scope, timeout;
  beforeEach(function () {
    module('CommonBusInfo');

    inject(function ($rootScope, $compile) {
      scope = $rootScope.$new();
      element = angular.element('<form><input id="Montid" ng-model="test" value="09" type="text"/><input id="yearId" " type="text" value="2015" month-next/></form>');
      $compile(element)(scope);
      scope.$digest();
    });
  });
  it('should set Month value to 1', function () {
    var x = element.find('input');
    x.triggerHandler('input');
    scope.$digest();

  });
});

i want to read Montid value to compare

Thank you, Chaitanya


回答1:


You can get the attribute with the attr function

it('should set Month value to 1', function () {
  var x = element.find('input');
  var inputId = x.attr('id');
  expect(inputId).toBe('Montid');
});


来源:https://stackoverflow.com/questions/32879799/unit-testing-directive-with-angularjs-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!