2017-07-24 1 views
1

Ich möchte meine Provider-Klasse testen, daher kann ich keine Spezifikationen für Provider schreiben.Wie schreibe ich eine Einheit Testspezifikation für einen Provider mit http-Anfrage in ionic2?

Mein Provider ist wie folgt:

service.ts

//imports are done correctly. 

@Injectable() 
export class Service { 

    constructor(private http: Http) { } 

    getGoogle():Observable<any> { 
     console.log("Inside service"); 
     return this.http.get('https://jsonplaceholder.typicode.com/posts/1'); 
    } 
} 

Mein page.ts ist wie folgt:

page.ts

//imports are done correctly. 

export class Page1 { 

    constructor(private service: Service, private navCtrl: NavController) { } 
    async get() { 
    console.log("inside get method"); 
    const data = await this.service.getGoogle().toPromise(); 
     console.log('The response is' , data); 
     } 
} 

service.spec.ts

//imports are done correctly 

describe('Service',() => { 
    let comp: Service; 
    let fixture: ComponentFixture<Service>; 
    let de: DebugElement; 

    beforeEach(async(() => { 
     TestBed.configureTestingModule({ 
      declarations: [], 
      imports: [ 
       IonicModule.forRoot(Service) 

      ], 
      providers: [Http] 
     }).compileComponents(); 

    })); 
    beforeEach(() => { 
     fixture = TestBed.createComponent(Service); 
     comp = fixture.componentInstance; 
     de = fixture.debugElement; 
    }); 
    afterEach(() => { 
     fixture.destroy(); 
    }); 
it('test the http request to te server',()=>{ 
      //code to test http request of the Service class 

}); 

}); 

Alle Importe richtig gemacht, nur die Logik der getGoogle zu testen() mit http.get() muss getestet werden.

Bitte helfen oder teilen Sie einige Links oder sagen Sie mir einige Schritte, um diese ionic2 Inhalte zu testen.

Danke

Antwort

0

This Rangle tutorial ein großartiger Ort zu starten.

Sie können Ihren Provider wie dieser

class MockService { 
    public data = 'Test data'; 

    getGoogle() { 
    return Observable.of(this.data); 
    } 
} 

Geben Sie es zu TestBed

TestBed.configureTestingModule({ 
    declarations: [ 
    Page1 
    ], 
    providers: [ 
    { provide: Service, useClass: MockService } 
    ] 
}); 

Und tick und fakeAsync verspotten verwenden, um den Asynchron-Betrieb

it('should get', fakeAsync(() => { 
    comp.get(); 
    tick(); 
    // If you want to assign the data to a class variable. If not, change the 
    // condition for whatever you want to test the method to do. 
    expect(comp.data).toEqual('Test data'); 
})); 
zu simulieren
Verwandte Themen