2017-03-15 24 views
11

Benim components.ts,Angular2 - i test durumda çalıştırmayı denediğinizde http çağrı Kod kapsama

Yani
getHomePageData() : void{ 
    this.homeservice.getHomePageData() 
      .subscribe(
       data => { 

          //console.log("response status ################### "+data.status); 
          //console.log("getUserData response ************ \n"+JSON.stringify(data)); 
          this.defaultFacilityId = data.response.defaultFacilityId; 
          this.defaultFacilityName = data.response.defaultFacilityName; 
          this.enterpriseId = data.response.enterpriseId; 
          this.enterpriseName = data.response.enterpriseName; 
          this.facilityList = data.response.facilityList; 
          this.userName = data.response.userName; 

          this.showDefaultPopoup(); 
         }, 
       error => { 
          console.error(error); 
          //this.errorMessage="Technical error - Contact Support team !" ; 
         } 
     ); 

    } 

benim component.spec.ts olduğunu

it('getHomePageData with SUCCESS - getHomePageData()',() => { 
    backend.connections.subscribe((connection: MockConnection) => { 
     //expect(connection.request.url).toEqual('http://localhost:8080/MSMTestWebApp/UDM/UdmService/Home/'); 
     expect(connection.request.url).toEqual('http://192.168.61.158:9080/GetUserData'); 

     expect(connection.request.method).toEqual(RequestMethod.Get); 
     expect(connection.request.headers.get('Content-Type')).toEqual('application/json'); 
     let options = new ResponseOptions({ 
     body: 
     { 
      "request": { "url": "/getUserData" }, 
      "response": { 
       "defaultFacilityName":"3M Health Information Systems", 
        "enterpriseId":"11.0", 
        "enterpriseName":"HSA Enterprise", 
        "defaultFacilityId": "55303.0", 
        "userName":"Anand" 
      }, 
      "error": "" 
     }, 
     status : 200 
     }); 

     connection.mockRespond(new Response(options)); 

    }); 

    backend.connections.subscribe((data) => { 
     //expect(data.response.facilityId).toEqual("55303.0"); 
     //expect(subject.handleError).toHaveBeenCalled(); 
    }) 

    service.getHomePageData().subscribe((data) => { 
      //expect(videos.length).toBe(4); 
      expect(data.response.defaultFacilityId).toEqual("55303.0"); 
      component.defaultFacilityId = data.response.defaultFacilityId; 
      component.defaultFacilityName = data.response.defaultFacilityName; 
      component.enterpriseId = data.response.enterpriseId; 
      component.enterpriseName = data.response.enterpriseName; 
      component.userName = data.response.userName; 
      console.log("$$$$$$$$$$$$$$$$**********$$$$$$$$$$$$$$$$$$$$$"); 
     }); 

    }); 

olduğunu. Geçti. Ancak, kod kapsamına bakarken, aşağıdaki kodun kırmızı ile gösterilen kodu kapsamaz. enter image description here

Lütfen kodun tamamını doldurmaya yardımcı olun. Teşekkürler.

+0

Örneğinizde bir sorun var. 'TestBed.configureTestingModule' bölümünü ekleyebilir misiniz? Geçtiğinde kaç tane testin testi var? Test etmek için "async"/'fakeAsync 'eklemeyi denediniz mi? –

+0

@HumanBeing Kapsam yapılandırması sağlayabiliyor musunuz, angular-cli veya özel webpack yapılandırmasını ne kullandınız? – BILL

cevap

2

JSON verilerini kullanıyor musunuz?

Alkış

testinde
+0

** service.ts ** içinde ** map ** kullanıyorum. ** component.ts ** 'da ** map ** fonksiyonunu kullanamıyorum. –

+0

Sanırım bir denemeye değer. Aksi takdirde, verilerinizi harita, service.ts kullandığınız yerlere almaya çalışın. – mlk

+0

In ** service.ts ** Ivan, yüzde 100 kapsama alanını kapsayabildi. Hem başarı hem de başarısızlık durumu.Burada ** component.ts ** olabilir, ** abone olabilir ** problem yaratır. –

5

gösterdiğin,

ngOnInit() { 
this.getHomePageData(); 
} 

getHomePageData() { 
this.http.get('your.json') 
    .map((res:Response) => res.json()) 
    .subscribe(
    data => { 
     this.YourData = data 
    }, 
    err => console.error(err), 
    () => console.log('ok') 
); 
} 

Umarım yardımcı olur: O zaman muhtemelen .subscribe().

.map((res:Response) => res.json()) 

böyle kodunuzu organize deneyin kullanmadan önce map() kullanmalıdır Burada getHomePageData() numaralı telefon numaranızdan

numaralı telefondan arama yapıyorsunuz 0

böyle testinizi bina deneyin:

import { fakeAsync, tick } from '@angular/core/testing'; 
... 
it('getHomePageData with SUCCESS - getHomePageData()', fakeAsync(() => { 
    backend.connections.subscribe((connection: MockConnection) => { 
    //expect(connection.request.url).toEqual('http://localhost:8080/MSMTestWebApp/UDM/UdmService/Home/'); 
    expect(connection.request.url).toEqual('http://192.168.61.158:9080/GetUserData'); 

    expect(connection.request.method).toEqual(RequestMethod.Get); 
    expect(connection.request.headers.get('Content-Type')).toEqual('application/json'); 
    let options = new ResponseOptions({ 
    body: 
    { 
     "request": { "url": "/getUserData" }, 
     "response": { 
      "defaultFacilityName":"3M Health Information Systems", 
       "enterpriseId":"11.0", 
       "enterpriseName":"HSA Enterprise", 
       "defaultFacilityId": "55303.0", 
       "userName":"Anand" 
     }, 
     "error": "" 
    }, 
    status : 200 
    }); 

    connection.mockRespond(new Response(options)); 

    }); 

    // If this function is not automatically called in the component initialisation 
    component.getHomePageData(); 
    tick(); 
    //you can call expects on your component's properties now 
    expect(component.defaultFacilityId).toEqual("55303.0"); 

}); 

FakeAsync artık beklentilerinizi yazmak için hizmet işlevine abone olmak zorunda böylece bir daha doğrusal bir tarzda testleri yazmak için izin verir. Bir FakeAsync sınama işlevinde, bir zaman geçidini simüle etmek için bir zaman uyumsuz işlemin gerçekleştiği ve kodunuzun akışına devam eden bir çağrıdan sonra tick() aramasını çağırabilirsiniz.

Bu konu hakkında daha fazla bilgi bulabilirsiniz: https://angular.io/docs/ts/latest/testing/#!#fake-async

DÜZENLEME - Hata Vaka

Eğer mockError aramalarını veya bağlantıda mockRespond kullanarak bir hata yanıtını ayarlayabilirsiniz hata mantığını test etmek için:

it('getHomePageData with ERROR- getHomePageData()', fakeAsync(() => { 
    backend.connections.subscribe((connection: MockConnection) => { 
    if (connection.request.url === 'http://192.168.61.158:9080/GetUserData') { 
     // mockError option 
     connection.mockError(new Error('Some error')); 
     // mockRespond option 
     connection.mockRespond(new Response(new ResponseOptions({ 
      status: 404, 
      statusText: 'URL not Found', 
     }))); 
    } 

    component.getHomePageData(); 
    tick(); 
    //you can call expects now 
    expect(connection.request.url).toEqual('http://192.168.61.158:9080/GetUserData'); 
    expect(connection.request.method).toEqual(RequestMethod.Get); 
    expect(connection.request.headers.get('Content-Type')).toEqual('application/json'); 
    expect('you can test your error logic here'); 
}); 

Abonelik içinde yaptığımız şey, herhangi bir zamanda GetUserData son noktanın hin bu test yöntemi bir hata döndürecektir.

Hata ve başarıları ayrı ayrı başarı sınamasında test ettiğimizden, istek seçeneklerinde hatayla ilgili ayarları eklememiz gerekmez.

+0

Değerli cevaplar için teşekkürler ... ** Başarı durumu ** için teminat gayet iyi. Şimdi kod kapsamı ** hata ** için ele alınmalıdır. Lütfen bana yardım edebilir misin? –

+0

Endişelenmeyin, hata durumunu eklemek için cevabı düzenledim – Borquaye

İlgili konular