Skip to content

Instantly share code, notes, and snippets.

@icfantv
Forked from robwormald/github_api.ts
Created June 20, 2016 16:00
Show Gist options
  • Save icfantv/0df342d48f8e14aeba05193b5d2fa81b to your computer and use it in GitHub Desktop.
Save icfantv/0df342d48f8e14aeba05193b5d2fa81b to your computer and use it in GitHub Desktop.
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
const GITHUB_API_URL = 'https://api.github.com';
export class Repository {
name: string;
full_name: string;
stargazers_count: number;
watchers_count: number;
constructor({name, full_name, stargazers_count, watchers_count}) {
this.name = name;
this.full_name = full_name;
this.stargazers_count = stargazers_count;
this.watchers_count = watchers_count;
}
}
@Injectable()
export class GithubAPI {
constructor(private http:Http) {}
getRepo(org:string, name:string): Observable<Repository> {
return this.http.get(`${GITHUB_API_URL}/repos/${org}/${name}`)
.map(res => res.json())
.map(repoData => new Repository(repoData));
}
}
import {GithubAPI, Repository} from './github_api';
import {Injector, provide} from 'angular2/core';
import {MockBackend, MockConnection} from 'angular2/http/testing';
import {HTTP_PROVIDERS, XHRBackend, Response, ResponseOptions} from 'angular2/http';
const ANGULAR_REPO_URL = 'https://api.github.com/repos/angular/angular';
const MOCK_API_RESPONSE = `
{
"id": 24195339,
"name": "angular",
"full_name": "angular/angular",
"stargazers_count": 2000,
"watchers_count" : 1000
}`;
export function main() {
describe('GithubAPI Service', () => {
let injector:Injector;
let backend:MockBackend;
let githubAPI:GithubAPI;
beforeEach(() => {
injector = Injector.resolveAndCreate([
HTTP_PROVIDERS,
provide(XHRBackend, {useClass: MockBackend}),
GithubAPI
]);
backend = injector.get(XHRBackend);
githubAPI = injector.get(GithubAPI);
});
it('should instantiate the mock backend', () => {
expect(githubAPI).toBeDefined();
});
it('should make a request to the Github API', (done) => {
backend.connections.subscribe((c:MockConnection) => {
expect(c.request.url).toEqual(ANGULAR_REPO_URL);
done();
});
githubAPI.getRepo('angular', 'angular').subscribe();
});
it('should make a return an instance of a Repository', (done) => {
backend.connections.subscribe((c:MockConnection) => {
c.mockRespond(new Response(new ResponseOptions({body: MOCK_API_RESPONSE})));
});
githubAPI.getRepo('angular', 'angular').subscribe((repo:Repository) => {
expect(repo instanceof Repository).toBe(true);
expect(repo.full_name).toEqual('angular/angular');
expect(repo.name).toEqual('angular');
expect(repo.watchers_count).toEqual(1000);
expect(repo.stargazers_count).toEqual(2000);
done();
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment