0

私はジャスミンテストに比較的慣れていないので、問題があります。私はこのディレクティブをテストしようとします:

指令

myApp.LoadingsDirective = function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div class="loading"><img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" width="20" height="20" /></div>',
        link: function (scope, element, attrs) {
            scope.$watch(
                function(scope) {
                    return scope.$eval(attrs.show);
                },
                function(val) {
                    if (val){
                        $(element).show();
                    }
                    else{
                        $(element).hide();
                    }
                })
        }
    }
}
    myApp.directive('loading', myApp.LoadingsDirective);

このディレクティブは、非同期リクエストの結果がそれを置き換えるまで、読み込みアイコンを表示するだけです。

私はこのようなことを試します:

テスト

describe('Testing directives', function() {
    var $scope, $compile, element;

    beforeEach(function() {
        module('myApp');

        inject(function($rootScope, _$compile_) {
            $scope = $rootScope.$new();
            $compile = _$compile_;
        });
    });

    it('ensures directive show the loading when show attribut is true', function() {
        // GIVEN
        var element = $compile('<div><loading show="true"> </loading></div>')($scope);
        var loadingScope = element.find('loading').scope();

        // WHEN
        loadingScope.$watch();

        // THEN
        expect(loadingScope.show).toBe('true');
    });
});

このタイプのディレクティブをテストする最良の方法は何ですか? 属性にアクセスしてテストする方法は?

4

1 に答える 1

1

私はいつもこのようにしています(コーヒースクリプトですが、アイデアはわかります):

'use strict';

describe 'Directive: yourDirective', ->
  beforeEach module('yourApp')

  # angular specific stuff
  $rootScope = $compile = $scope = undefined
  beforeEach inject (_$rootScope_, _$compile_) ->
    $rootScope = _$rootScope_
    $scope = $rootScope.$new()
    $compile = _$compile_

  # object specific stuff
  element = createElement = undefined
  beforeEach inject () ->
    createElement = () ->
      element = angular.element("<your-directive></your-directive>")
      $compile(element)($scope)
      $scope.$digest()

  it "should have a headline", ->
    createElement()
    element.find("a").click()
    $scope.$apply()
    expect(element.find("input").val()).toEqual("foobar")
    expect($scope.inputModel).toEqual("foobar")

そして、これはディレクティブである可能性があります:

<your-directive>
  <a ng-click="spanModel='foobar'">set inputModel</a>
  <input ng-model="inputModel">
</your-directive>

まず、要素の作成を関数に抽出します。これにより、ディレクティブを作成する前に初期設定を行うことができます。

次に、ディレクティブに対していくつかのアクションを実行します。このアクションをスコープに適用したい場合 (jasmine では、Angular のダイジェスト サークルの内側にいないことを思い出してください)、$scope.$apply()orを呼び出す必要$scope.$digest()があります (正確な違いが何であったか、今は思い出せません)。

<a>上の例では、要素をクリックすると、これに がng-click添付されています。これにより、inputModelスコープ変数が設定されます。

テストされていませんが、アイデアは得られます

于 2014-07-23T11:20:35.747 に答える