Skip to content

Instantly share code, notes, and snippets.

View IAfanasovMob's full-sized avatar

Igor Afanasov IAfanasovMob

View GitHub Profile
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class GitHubApiVersionInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url.startsWith('https://api.github.com/')) {
it(`should add Accept header with value 'application/vnd.github.v3.star+json'
when requested https://api.github.com/*`, () => {
client.get('https://api.github.com/anything').subscribe();
const requests = httpMock.match({ method: 'get' });
expect(requests[0].request.headers.get('Accept'))
.toEqual('application/vnd.github.v3.star+json');
});
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule
],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: GitHubApiVersionInterceptor,
multi: true,
}]
<div *ngIf='errorMessage'
class="alert alert-danger"
role="alert">
{{errorMessage}}
</div>
loadStarred() {
this.http.get<Repo[]>(`https://api.github.com/users/${this.userName}/starred`)
.pipe(
tap(
response => {
this.repos = response;
this.errorMessage = null;
}
),
catchError(error => {
it('should show error message when request fails', async () => {
component.userName = 'IAfanasov';
fixture.debugElement.query(By.css('button')).nativeElement.click();
const request = httpMock.expectOne('https://api.github.com/users/IAfanasov/starred');
request.error(null);
fixture.detectChanges();
await fixture.whenRenderingDone();
const alert = fixture.debugElement.query(By.css('.alert-danger'));
loadStarred() {
this.http.get<Repo[]>(`https://api.github.com/users/${this.userName}/starred`)
.pipe(
tap(response => this.repos = response)
)
.subscribe();
}
it('should save list of starred repos from GitHub API when response received', () => {
component.userName = 'IAfanasov';
const repos: Repo[] = [{
id: 1,
created_at: '22-09-2019',
name: 'mock',
stargazers_count: 1000,
updated_at: '30-09-2019'
}];
export interface Repo {
id: number;
created_at: string;
name: string;
stargazers_count: number;
updated_at: string;
}
@IAfanasovMob
IAfanasovMob / app-component.ts
Last active October 8, 2019 11:57
app-component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
userName: string;