如何使用jasmine在指令中编写指令的测试用例

时间:2016-10-24 09:27:11

标签: angularjs unit-testing jasmine karma-jasmine

我使用jasmine testcase框架和karma testcase runner为我的指令编写了一个测试。 在我的项目中,我已经有一个名为

的指令
<parent-directive></parent-directive>

我尝试将该父指令包含在另一个名为

的指令中

<child-directive></child-directive>.

父指令元素被转换为名为 SampleComponents 的组件,并包含在子指令中

Sample.js

'use strict'

angular.module('Sample')
  .directive('SampleHeader', SampleHeader)

function SampleHeader () {
  return {
    restrict: 'A',
    templateUrl: 'header/header.html',
    scope: {},
    controller: function ($scope) {
      $scope.logoutHeader = function () {
        console.log('Logout call back')
        require('electron').remote.app.quit()
      }
    }
  }
}

SampleSpec.js

describe('SampleHeader', function () {
    var $compile, $rootScope, elements, scope, controller


    beforeEach(module('Sample'))
    beforeEach(module('SampleComponenets'))
    beforeEach(module('ngAnimate'))
    beforeEach(module('ngRoute'))
    beforeEach(module('ngMaterial'))
    beforeEach(module('ngCookies'))
    beforeEach(module('datatables'))


    beforeEach(inject(function (_$compile_, _$rootScope_, _$q_,_$controller_) {

        deferred = _$q_.defer()
        $compile = _$compile_
        $rootScope = _$rootScope_
        controller = _$controller_
        scope = $rootScope.$new()

        elements = angular.element('<sample-header></sample-header>')
        $compile(elements)($rootScope.$new())
        $rootScope.$digest()
        controller = elements.controller('SampleHeader')
        scope = elements.isolateScope() || elements.scope()
        scope.$digest()

    }))

    it('should check logoutHeader is called', function () {scope.logoutHeader()
    })
})

1 个答案:

答案 0 :(得分:3)

限制:&#39; A&#39; - &gt; 您似乎创建了一个属性指令,因此您应该将该指令编译为属性 (例如,elements = angular.element('<div sample-header></div>')

describe('SampleHeader', function () {
    var $compile, $rootScope, elements, scope, controller


    beforeEach(module('Sample'))
    beforeEach(module('SampleComponenets'))
    beforeEach(module('ngAnimate'))
    beforeEach(module('ngRoute'))
    beforeEach(module('ngMaterial'))
    beforeEach(module('ngCookies'))
    beforeEach(module('datatables'))


    beforeEach(inject(function (_$compile_, _$rootScope_, _$q_,_$controller_) {

        deferred = _$q_.defer()
        $compile = _$compile_
        $rootScope = _$rootScope_
        controller = _$controller_
        scope = $rootScope.$new()

        elements = angular.element('<div sample-header></div>')
        $compile(elements)($rootScope.$new())
        $rootScope.$digest()
        controller = elements.controller('SampleHeader')
        scope = elements.isolateScope() || elements.scope()
        scope.$digest()

    }))

    it('should check logoutHeader is called', function () {scope.logoutHeader()
    })
})