1

ページ上のコントローラーとは別のコントローラーを使用する AngularJS ディレクティブの単体テストを作成しようとしています。ただし、テスト内からそのコントローラーにアクセスする方法が見つかりません。

これが私の指示です:

'use strict';
angular.module('myapp.directives')
  .directive('searchButton', function () {
    function SearchButtonCtrl ($scope, $location) {
      $scope.search = function () {
        $location.path('/search');
        $location.search(q, $scope.query.w);
      };
    }
    return {
      template: '<input type="text" ng-model="query.q">',
      controller: SearchButtonCtrl,
      restrict: 'E'
    };
  });

アクセスできますSearchButtonCtrlか?または、アクセスできるようにコードを構造化するより良い方法はありますか?

4

1 に答える 1

2

この場合、最終的にコントローラーにアクセスする方法は、コントローラーがテスト入力を形成する HTML スニペットからそのスコープに配置する関数を使用することです。

注: ここでジャスミン スパイを使用するのはやり過ぎかもしれません。引数を $location.path() および/または $location.search() に一致させるための適切なメソッドを調べる時間はありませんでしたが、これは探している観察場所へのフックを見つけるのに十分なはずです。

'use strict';

describe('Directive: Search', function() {

    var element, $location;

    // Load your directive module with $location replaced by a test mock.
    beforeEach( function() {
        module('myapp.directives'), function() {
            $provide.decorator('$location', function($delegate) {
                $delegate.path = jasmine.createSpy();
                $delegate.search = jasmine.createSpy();

                return $delegate;
            });
        });

        inject(function(_$location_) {
            $location = _$location_;
        });
    });

    it('changes the path', function() {
        // Arrange to trigger your directive code
        element = $element.html('<span ng-init="query.q = 'xyz'"><search><span ng-init="search()"></span></search></span>' );

        // Express your directive's intended behavior
        expect($location.path).toHaveBeenCalled();
    });

    it('changes a search param', function() {
        // Arrange to trigger your directive code
        element = $element.html('<span ng-init="query.q = 'xyz'"><search><span ng-init="search()"></span></search></span>' );

        // Express your directive's intended behavior
        expect($location.search).toHaveBeenCalled();
    });
});
于 2013-06-27T03:33:47.060 に答える