Data Services

Last updated 6 months ago

Spector makes testing data services, which use the Angular HTTP module, a lot easier. For example, let's say that you have data service with two methods, one performs a GET and one a POST.

export class TodosDataService {
constructor(private http) {}
get() {
return this.http.get('todos');
}
post(id: number) {
return this.http.post('todos', { id });
}
}
import { TodosDataService } from './todos-data.service';
import { createHTTPFactory, HTTPMethod } from '@netbasal/spectator';
describe('HttpClient testing', () => {
let http = createHTTPFactory<TodosDataService>(TodosDataService);
it('can test HttpClient.get', () => {
let { dataService, controller, expectOne } = http();
dataService.get().subscribe();
expectOne('todos', HTTPMethod.GET);
});
it('can test HttpClient.post', () => {
let { dataService, controller, expectOne } = http();
dataService.post(1).subscribe();
const req = expectOne('todos', HTTPMethod.POST);
expect(req.request.body['id']).toEqual(1);
});
});

First, you need to create an HTTP factory by using the createHTTPFactory() function, passing the data service that you want to test.

The createHTTPFactory() returns a function which can be called to get an instance of SpectatorHTTP with the following properties:

  • controller - A proxy for Angular HttpTestingController

  • httpClient - A proxy for Angular HttpClient

  • dataService - The data service instance (todosService)

  • get<T> - A proxy for Angular TestBed.get()

One useful method is expectOne() which lets to expect that a single request was made which matches the given URL and it's method, and return its mock request. expectOne(url: string, method: HTTPMethod) => TestRequest

it("should work with external service", fakeAsync(() => {
let { dataService, controller, expectOne, get } = http();
get(UserService).getUser.andCallFake(() => {
return defer(() => Promise.resolve({}));
});
const req = dataService.requestWithExternalService().subscribe();
tick();
expectOne("two", HTTPMethod.GET);
})
);