【问题标题】:How do I test the angularjs directive?如何测试 angularjs 指令?
【发布时间】:2014-01-13 08:20:30
【问题描述】:
appD.directive "check",->
    restrict: "EA"
    require: "ngModel"
    link: (scope, el, attrs, ngModelCtrl) ->
        old_val = scope.budget
        el.on "blur", (e) ->
            new_val = el.val()
            if new_val < old_val+5000      
                el.val(old_val) 

如何为这个 angularjs 指令编写测试?

【问题讨论】:

  • 你能修复缩进吗? Coffeescript 对空格敏感,因此很重要。
  • 好吧,现在我认为缺少一些信息。什么是范围预算?为什么要模糊?为什么不看元素的值呢?

标签: angularjs coffeescript angularjs-directive jasmine bdd


【解决方案1】:

这就是使用jasmine 框架进行测试的样子

describe "testing check directive", ->
  scope = undefined
  element = undefined

  #loading modules that we need for tests
  beforeEach module("appD")

  #loading our directive template for testing.
  beforeEach inject(($templateCache) ->
    directiveTemplate = null
    templateUrl = "../../../path/to/directive/template.html"
    $.ajax
      url: templateUrl
      isLocal: true
      success: (content) ->
        directiveTemplate = content

      async: false
      dataType: "html"

    $templateCache.put templateUrl, directiveTemplate
  )

  # Our tests start hear
  testValue = "6000"
  describe "When processing 'check' directive and element value = '" + testValue + "'", ->
    beforeEach inject(($compile, $rootScope) ->
      scope = $rootScope

      #The element with check directive
      element = angular.element("<input check value='" + testValue + "'></div>")

      $compile(element) scope
      element = $(element)
      element.scope().$apply()
    )
    budget = 100
    describe "And budget is  " + budget, ->
      beforeEach ->
        scope.budget = budget
        scope.$apply()
        element.blur()

      it "Than element value should stay the same = " + testValue, ->
        expect(element.val()).toEqual testValue


    budget = 2000
    describe "And budget is  " + budget, ->
      beforeEach ->
        scope.budget = budget
        scope.$apply()
        element.blur()

      it "Than element value should be equal to budget value", ->
        expect(element.val()).toEqual budget

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    相关资源
    最近更新 更多