Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
angular2 service test based on angular2-seed with jasmine
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