2017-11-17 1 views
0

서비스를 호출하고 HTTP로부터 응답을 받기위한 테스트 케이스를 작성하려고합니다. 100,이 코드는각도 4/5 단위 테스트 케이스. 서비스에 들어갑니다.

import { Injectable } from '@angular/core'; 
import { HttpClient } from '@angular/common/http'; 

@Injectable() 
export class SampleDataService { 

    constructor(private http:HttpClient) { } 

    getData(){ 
    return this.http.get("http://jsonplaceholder.typicode.com/posts"); 
    } 
} 

app.component 예외를

it('Should call HTTP!', inject([SampleDataService], (sampleDataService) => { 
    expect(100).toBe(12); //<== This gives me correct exception i.e Expected 100 to be 12. 
    sampleDataService.getData().subscribe(
    (data) => { 
     console.log('ngOnInit', data.length); // here data.length is 100 
     expect(data.length).toBe(12); // This does not throw any exception 
    }); 
})); 

SampleDataService.ts를 포기하지 않습니다

expect(data.length).toBe(12);에도 data.length 불구하고 :

Reference 이제 문제는 다음과 같습니다 .spec.ts

import { TestBed, async, ComponentFixture,inject } from '@angular/core/testing'; 
import { RouterTestingModule } from '@angular/router/testing'; 
import { AppComponent } from './app.component'; 
import { ReactiveFormsModule, FormsModule } from '@angular/forms'; 
import { SampleDataService } from './services/sample-data.service'; 
import { HttpClientModule,HttpClient } from '@angular/common/http'; 

describe('AppComponent',() => { 
    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     imports: [ 
     RouterTestingModule, 
     HttpClientModule, 
     FormsModule, 
     ReactiveFormsModule 
     ], 
     declarations: [ 
     AppComponent 
     ], 
     providers:[SampleDataService] 
    }).compileComponents(); 
    })); 
    it('Should call HTTP!', inject([SampleDataService], (sampleDataService) => { 
    expect(100).toBe(12); 
    sampleDataService.getData().subscribe(
     (data) => { 
     console.log('ngOnInit', data.length); 
     expect(data.length).toBe(12); 
     }); 
    })); 
}); 

답변

0

일반적으로 유닛 테스트 중에 Http 호출을 모의하고 싶습니다. 하지만 실제로 원하지 않으면 http가 비동기식이기 때문에 응답을 받으면 테스트를 종료해야합니다.

+0

코드가 매력처럼 작동하지만 코드가 무엇인지 말해 주실 수 있습니까? 내 코드가 잘못 됐어? –

+0

요청을 보낸 즉시 메서드가 반환되므로 Jasmine은 비동기 응답을 받거나 검사 할 때까지 기다리는 것을 알지 못합니다. –

+0

하지만 거기에'구독하기 '를 사용 했으므로 제대로 된 일이 아니 었습니까? –

관련 문제