Skip to content

Instantly share code, notes, and snippets.

@textbook
Last active May 13, 2020 15:31
Show Gist options
  • Save textbook/fd7c8a66a8f650634c8e65be4debbf25 to your computer and use it in GitHub Desktop.
Save textbook/fd7c8a66a8f650634c8e65be4debbf25 to your computer and use it in GitHub Desktop.
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { DemoService } from './demo.service';
fdescribe('DemoService', () => {
let service: DemoService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule
],
});
service = TestBed.inject(DemoService);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
it('should be created', () => {
service.makeRequest('hello').subscribe((result) => {
expect(result).toEqual({ foo: 'bar' });
});
httpMock.expectOne('domain.ext/hello').flush({ foo: 'bar' });
});
});
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { of, Observable, forkJoin } from 'rxjs';
import { flatMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DemoService {
constructor(private http: HttpClient) { }
makeRequest(path: string): Observable<any> {
return forkJoin([
this.createUri(path),
this.createHeaders()
]).pipe(
flatMap(([url, headers]) => this.http.get(url, { headers }))
);
}
private createHeaders(): Observable<HttpHeaders> {
return of(new HttpHeaders());
}
private createUri(path: string): Observable<string> {
return of(`domain.ext/${path}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment