2016-11-23 4 views
1

각도 응용 프로그램에 Jasmine을 사용하여 테스트를 작성하고 있습니다. 모든 검사가 끝나고 있습니다. 여기Jasmine : 약속을 반환하는 함수 테스트

class xyz implements ng.IComponentController { 
    private myList: ng.IPromise<MyList[]> ; 
    //declare necessary variables 
    /* @ngInject */ 
    constructor(private ListService: ListService, 
      ) { 
    this.myList = this.ListService.getList(); 
    } 

    public onChange(): void { 
    this.isNameUnique(this.name).then(function(unique){ 
     scope.isUnique = unique; 
     scope.errorNameInput = !reg.test(scope.name) || !scope.isUnique; 
     scope.myFunction({ 
     //do something 
     }); 
    }); 
    } 

    public isNameUnique(name: string): ng.IPromise<boolean> { 
    return this.myList 
    .then(
     (names) => { 
     _.mapValues(names, function(name){ 
      return name.uuid.toLowerCase(); 
     }); 
     return (_.findIndex(names, { uuid : uuid.toLowerCase() }) === -1) ? true : false; 
    }); 
    } 
} 

을 나는 생성자 자체 내 목록을 미리 채울 ListService를 사용하고 (그래서 서비스 번만 호출) : 다음과 같은 내 클래스 보인다. 그런 다음 onChange 메서드에서 이름이 고유한지 확인하려면 입니다. isNameUnique가 불린 약속을 리턴합니다. 이제 테스트를 위해 100 % 커버리지를 얻으려고합니다. 내가 isNameUnique 메서드를 테스트하는 것에 대해 혼란스러워진다.

나는이 테스트 라인을 커버하는 기대

this.$scope.myFunction = jasmine.createSpy('myFunction'); 
    it('should ...', function() { 
     this.view.find(NAME_INPUT).val('blue').change(); // my view element. 
     this.getList.resolve(myList); 
     this.controller.isNameUnique('blue').then(function (unique) { 
     expect(unique).toEqual(false); //since blue is already in my json 
     expect(this.controller.errorNameInput).toEqual(true); //since its not unique, errornameinput will be set to true 
     expect(this.$scope.myFunction).toHaveBeenCalled(); 
     }); 
    }); 

(가정 myList에 내가 서비스에서 얻을 것이다 응답과 비슷한 JSON입니다) : 내 첫 번째 테스트는 myFunction()scope.errorNameInput = !reg.test(scope.name) || !scope.isUnique 및 호출하지만 여전히 쇼 폭로 된. 이유를 모르겠다.

내가 Angular and Jasmine을 처음 접했으므로 다른 점이 있으면 알려 주시기 바랍니다. 감사.

답변

0

$scope.$digest()으로 전화하여 테스트에서 해결할 수 있습니다. 이것에 대해 자세히 설명하는 편리한 자습서가 있습니다. here

희망이 있습니다!

+1

저는 약속이 이미 해결되고 있다고 생각했기 때문에 그것이 저에게 유일성에 대한 정확한 결과를 제공하고 시험이 통과되는 이유입니다. 내가 이것에 관해 읽게 해주세요. 감사. –

+0

당신의 약속 해결 이론을 테스트하는 것은 쉽습니다.'then()'에서'console.log()'를 집어 넣고 테스트에서 히트를 치는지 볼 수 있습니다 :) –

+0

여기 Angular 1.x (동일한 원칙이 여전히 적용됨) : http://www.bradoncode.com/blog/2015/07/13/unit-test-promises-angualrjs-q/ –

관련 문제