I am trying to test a function in my service that returns an observable (BehaviorSubject).
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class TopicsService {
private topics = [];
private obs = new BehaviorSubject<any>(this.topics);
constructor(private http: HttpClient) {}
getTopics(): BehaviorSubject<any> {
if (!this.topics.length) {
this.http.get('http://localhost:8089/topics')
.subscribe(
(topicsData: any) => {
this.topics = topicsData;
this.obs.next(this.topics);
}
);
}
return this.obs;
}
Then I have created a mockResponse object that I expect to receive in the Http fake call. Then I call the getTopics() function and I subscribe to the Observable and I expect that what comes is actually the body of the response:
import { TestBed, inject } from '@angular/core/testing';
import { HttpClient, HttpHandler } from '@angular/common/http';
import { ConnectionBackend, ResponseOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { TopicsService } from './topics.service';
describe('TopicsService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
TopicsService, HttpClient, HttpHandler,
{ provide: ConnectionBackend, useClass: MockBackend }
]
});
});
describe('#getTopics()', () => {
it('should be created', inject([TopicsService], (service: TopicsService) => {
expect(service).toBeTruthy();
}));
it('should return a BehaviourSubject<any<Topic>>',
inject([TopicsService, ConnectionBackend], (service: TopicsService, mockBackend) => {
const mockResponse = {
name: 'Chess',
decription: 'Best chess courses'
};
mockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(mockResponse)
})));
});
service.getTopics().subscribe((topicData) => {
expect(topicData.length).toBe(1);
expect(topicData.name).toEqual('Chess');
expect(topicData.description).toEqual('Best chess courses');
});
}));
});
});
I am obviously doing something wrong, but I can't seem to get it. Thanks a lot in advance!
Aucun commentaire:
Enregistrer un commentaire