prosource

각도로 절연 스코프 지시어를 테스트하는 방법JS

probook 2023. 3. 4. 15:00
반응형

각도로 절연 스코프 지시어를 테스트하는 방법JS

Angular에서 격리된 스코프를 테스트하는 좋은 방법은 무엇입니까?JS

JSFiddle 표시 단위 테스트

지시 스니펫

    scope: {name: '=myGreet'},
    link: function (scope, element, attrs) {
        //show the initial state
        greet(element, scope[attrs.myGreet]);

        //listen for changes in the model
        scope.$watch(attrs.myGreet, function (name) {
            greet(element, name);
        });
    }

디렉티브가 변경을 리슨하고 있는지 확인하고 싶다.분리된 범위에서는 동작하지 않습니다.

    it('should watch for changes in the model', function () {
        var elm;
        //arrange
        spyOn(scope, '$watch');
        //act
        elm = compile(validHTML)(scope);
        //assert
        expect(scope.$watch.callCount).toBe(1);
        expect(scope.$watch).toHaveBeenCalledWith('name', jasmine.any(Function));
    });

업데이트: 예상된 감시자가 자스코프에 추가되었는지 확인하고 작동시켰지만, 매우 취약하며 아마도 문서화되어 있지 않은 방식으로 접근기를 사용할 수 있습니다(예고 없이 변경될 수 있습니다).

//this is super brittle, is there a better way!?
elm = compile(validHTML)(scope);
expect(elm.scope().$$watchers[0].exp).toBe('name');

업데이트 2: 말했듯이 이것은 부서지기 쉽습니다!이 아이디어는 여전히 작동하지만 Angular의 새 버전에서는 작동합니다.접근자가 변경된 JS:scope()로.isolateScope():

//this is STILL super brittle, is there a better way!?
elm = compile(validHTML)(scope);                       
expect(elm.isolateScope().$$watchers[0].exp).toBe('name');

angular element api 문서를 참조하십시오.element.scope()사용하면 디렉티브의 스코프 속성에서 정의한 요소의 스코프를 얻을 수 있습니다.element.isolateScope()사용하면 분리된 전체 범위를 얻을 수 있습니다.예를 들어 디렉티브가 다음과 같은 경우:

scope : {
 myScopeThingy : '='
},
controller : function($scope){
 $scope.myIsolatedThingy = 'some value';
}

그러면 테스트의 호출 요소.scope()가 반환됩니다.

{ myScopeThingy : 'whatever value this is bound to' }

그러나 element.isolateScope()를 호출하면

{ 
  myScopeThingy : 'whatever value this is bound to', 
  myIsolatedThingy : 'some value'
}

이것은 각도 1.2.2 또는 1.2.3의 경우로, 정확히는 알 수 없습니다.이전 버전에서는 element.scope()밖에 없었습니다.

할수있습니다var isolateScope = myDirectiveElement.scope()격리 스코프를 가져옵니다.

$watch가 호출된 것을 굳이 테스트할 필요는 없지만..앱을 테스트하는 것보다 angularjs를 테스트하는 것이 더 중요합니다.하지만 이건 질문의 예시일 뿐인 것 같아요.

로직을 다른 컨트롤러로 이동합니다.즉, 다음과 같습니다.

//will get your isolate scope
function MyCtrl($scope)
{
  //non-DOM manipulating ctrl logic here
}
app.controller(MyCtrl);

function MyDirective()
{
  return {
    scope     : {},
    controller: MyCtrl,
    link      : function (scope, element, attrs)
    {
      //moved non-DOM manipulating logic to ctrl
    }
  }
}
app.directive('myDirective', MyDirective);

다른 컨트롤러와 마찬가지로 후자를 테스트합니다.스코프 오브젝트를 직접 전달합니다(예를 들어 컨트롤러 섹션 참조).

테스트에서 $watch를 트리거해야 할 경우 다음을 수행합니다.

describe('MyCtrl test', function ()
{
  var $rootScope, $controller, $scope;

  beforeEach(function ()
  {
    inject(function (_$rootScope_, _$controller_)
    {
      // The injector unwraps the underscores (_) from around the parameter names when matching
      $rootScope = _$rootScope_;
      $controller = _$controller_;
    });

    $scope = $rootScope.$new({});
    $scope.foo = {x: 1}; //initial scope state as desired
    $controller(MyCtrl, {$scope: $scope}); //or by name as 'MyCtrl'
  });

  it('test scope property altered on $digest', function ()
  {
    $scope.$digest(); //trigger $watch
    expect($scope.foo.x).toEqual(1); //or whatever
  });
});

격리된 범위에서는 이것이 가능한지 잘 모르겠습니다(누군가 제가 틀렸다는 것을 증명해 주셨으면 합니다).디렉티브로 작성되는 격리 스코프는 격리되어 있기 때문에 디렉티브의 $watch 메서드는 유닛테스트에서 감시하고 있는 스코프와 다릅니다.범위: {}을(를) 범위: 참으로 변경하면 지시 범위가 프로토타입으로 상속되며 테스트를 통과해야 합니다.

최적의 솔루션은 아닌 것 같습니다.경우에 따라서는 (대부분) 범위를 분리하는 것이 좋습니다.

언급URL : https://stackoverflow.com/questions/17371836/how-to-unit-test-isolated-scope-directive-in-angularjs

반응형