Created
June 28, 2016 13:42
-
-
Save geekrumper/0de2a9a9b2874a1a6838f7fc3349c7bf to your computer and use it in GitHub Desktop.
angular2 service test based on angular2-seed with jasmine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {provide, ReflectiveInjector} from '@angular/core'; | |
import {BaseRequestOptions, ConnectionBackend, Http, HTTP_PROVIDERS, Response, ResponseOptions} from '@angular/http'; | |
import {MockBackend} from '@angular/http/testing'; | |
import {Observable} from 'rxjs/Observable'; | |
//imaginary service and model | |
import {DataService} from '../index'; | |
import {Data} from '../model/index'; | |
export function main() { | |
//---------------------------- RESPONSE BODY OBJECT ----------------------------// | |
const responseBody:any = { | |
'list': [ | |
{ | |
'Id': 12345678, | |
'name': 'string', | |
'street': 'string', | |
'streetNumber': 'string', | |
'zipCode': 'string', | |
'city': 'string', | |
'country': 'string', | |
'additionalAddress': 'string', | |
'nestedList': [ | |
{ | |
'Id': 0, | |
'Name': 'string', | |
} | |
] | |
} | |
], | |
'message': '', | |
'exception': null | |
}; | |
//---------------------------- RESPONSE BODY OBJECT ----------------------------// | |
describe('Data Service GET all data', () => { | |
let dataService:DataService; | |
let backend:MockBackend; | |
let initialResponse:any; | |
beforeEach(() => { | |
let injector = ReflectiveInjector.resolveAndCreate([ | |
HTTP_PROVIDERS, | |
DataService, | |
BaseRequestOptions, | |
MockBackend, | |
provide(Http, { | |
useFactory: function (backend:ConnectionBackend, defaultOptions:BaseRequestOptions) { | |
return new Http(backend, defaultOptions); | |
}, | |
deps: [MockBackend, BaseRequestOptions] | |
}) | |
]); | |
dataService = injector.get(DataService); | |
backend = injector.get(MockBackend); | |
const expectedUrl = 'http://localhost:9000/1/api'; | |
let connection:any; | |
backend.connections.subscribe((c:any) => { | |
connection = c; | |
//test if service is targeting the correct url | |
expect(connection.request.url).toBe(expectedUrl); | |
}); | |
initialResponse = dataService.getAll(); | |
connection.mockRespond(new Response(new ResponseOptions({body: JSON.stringify(responseBody)}))); | |
}); | |
it('should return an Observable when get called', () => { | |
expect(initialResponse).toEqual(jasmine.any(Observable)); | |
}); | |
it('should resolve to list of data with one object when called', () => { | |
let responseData:Data; | |
initialResponse.subscribe((data:Data) => responseData = data); | |
expect(responseData.list.length).toBe(1); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment