2017-10-30 4 views
2

안녕하세요 저는 다음 각도 서비스에 대한 재스민 단위 테스트를 작성하려고합니다.각도 2+ 약속 단위 테스트

그러나 반환 값 약속 테스트를 작성하는 방법에 어려움을 겪고 있으며 정교한 리소스를 찾을 수 없습니다.

대부분의 투쟁은 반환 된 약속 내에서 호출 된 것을 테스트하는 방법을 모르는 것에서 비롯됩니다.

예를 들어, 나는지도 인스턴스 new google.maps.Map(el, mapOptions)

각도 2+ 전문가 날 약속을 작성하는 사양을 이해하는 데 도움이 수와 this.createMap() 호출 this._mapResolver를 호출 테스트하려면? 또는 배울 참조를? @ArmenVardanyan

describe('Service: GoogleMapsAPIWrapper',() => { 

    const loaderServiceStub = { 
    load:() => Promise.resolve() 
    }; 

    let service; 


    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     providers: [ 
     GoogleMapsAPIWrapper, 
     {provide: MapsAPILoader, useValue: loaderServiceStub} 
     ] 
    }); 
    })); 

    beforeEach(async(inject([GoogleMapsAPIWrapper], (_service: GoogleMapsAPIWrapper) => { 
    service = _service; 
    }))); 


    it('should be created',() => { 
    expect(service).toBeTruthy(); 
    }); 

    it('should be call _mapResolver with specified arguments', async(() => { 
    const elem = document.createElement('div'); 
    const spyOnCreateMap = spyOn(service, '_mapResolver'); 
    service.createMap(elem, {}) 
     .then(() => { 
     expect(spyOnCreateMap).toHaveBeenCalled(); 
     expect(spyOnCreateMap).toHaveBeenCalledWith(new google.maps.Map(elem, {})); 
     }); 
    })); 

}); 
+0

정확히 테스트 하시겠습니까? Google Maps API가 실제로 작동합니까? 아니면 메서드가 실제로 약속을 반환합니까? –

+0

@ArmenVardanyan 답장을 보내 주셔서 감사합니다. createMap() 메소드의 경우 this._mapResolver가 올바른 인수로 호출되었는지 확인하고 싶습니다. setMapOptions() 메소드의 경우 m.setOptions가 (options)로 호출되었는지 확인하고 싶습니다. 이미 Google지도 api가 실제로 다른 파일에서 작동하는지 확인했습니다. –

+0

그래, 내가 대답을 제공하려고 노력합니다 –

답변

2

에 의해 제안

declare let google: any; 

/** 
* Wrapper class that handles the communication with the Google Maps Javascript 
* API v3 
*/ 
@Injectable() 
export class GoogleMapsAPIWrapper { 
    private _map: Promise<mapTypes.GoogleMap>; 
    private _mapResolver: (value?: mapTypes.GoogleMap) => void; 

    constructor(private _loader: MapsAPILoader, private _zone: NgZone) { 
    this._map = 
     new Promise<mapTypes.GoogleMap>((resolve:() => void) => { this._mapResolver = resolve; }); 
    } 

    createMap(el: HTMLElement, mapOptions: mapTypes.MapOptions): Promise<void> { 
    return this._loader.load().then(() => { 
     const map = new google.maps.Map(el, mapOptions); 
     this._mapResolver(<mapTypes.GoogleMap>map); 
     return; 
    }); 
    } 

    setMapOptions(options: mapTypes.MapOptions) { 
    this._map.then((m: mapTypes.GoogleMap) => { m.setOptions(options); }); 
    } 
} 

솔루션은 내가 제대로 NgZone의 INT 테스트를 주입하는 방법을 기억하지 않지만, 내가 볼로 귀하의 질문에 무관하다. 따라서 MapsAPILoader 서비스를 조롱하고 _mapResolver을 테스트하면됩니다.

const loaderServiceStub = { 
 
    load:() => Promise.resolve() 
 
}; 
 

 
describe('GoogleMapsAPIWrapper',() => { 
 
    beforeEach(() => { 
 
    TestBed.configureTestingModule({ 
 
     providers: [ 
 
     GoogleMapsAPIWrapper, 
 
     {provide: MapsAPILoader, useValue: loaderServiceStub} 
 
     ] 
 
    }); 
 
    }); 
 

 
    it('should be created', inject([GoogleMapsAPIWrapper], (service: GoogleMapsAPIWrapper) => { 
 
    expect(service).toBeTruthy(); 
 
    })); 
 

 
    it('should be call _mapResolver with specified arguments', inject([GoogleMapsAPIWrapper], (service: GoogleMapsAPIWrapper) => { 
 
    const spyOnCreateMap = spyOn(service, '_mapResolver'); 
 
    service.createMap(new HTMLDivElement(), {/*options */}); 
 
    expect(spyOnCreateMap).toHaveBeenCalled(); 
 
    })); 
 
});

그래서 당신은 기본적으로 load가 호출 될 때 바로 해결 약속을 반환 로더 서비스를 조롱하고 _mapResolver가 호출되었는지 확인합니다.

const map = new google.maps.Map(el, mapOptions); 
this._mapResolver(<mapTypes.GoogleMap>map); 

then 메서드에 전달 된 콜백 내에서 생성되는 맵이 있습니다,하지만 당신은 그 객체가 될 것입니다 무엇인지 알 수 없다 : 그러나 제공된 인수가 정확 경우가 있기 때문에이 라인, 확인할 수 없습니다. 시도해 볼 수 있습니다

expect(spyOnCreateMap).toHaveBeenCalledWith(new google.maps.Map(el, mapOptions)); 

그러나 나는 거의 작동하지 않을 것이라고 확신합니다. 같은 문제는 당신이 쓰고 싶은 두 번째 테스트와 함께 간다. _map 약속은 setOptions 메서드를 가진 객체를 반환 할 것이지만 그 객체가 무엇이 될지 정말로 모른다. 아니면 그 약속을 모의해야하고 조롱 한 setOptions 메서드가 호출되었는지 확인해야합니다.

+0

toHaveBeenCalledWith 잘 작동하지만 나는 그것을 '비공개 콜백으로 포장해야했다() –

관련 문제