I try to make some tests for my service. Which are mostly Rest-calls. But some of my Rest-calls have HttpHeaders. How can I make a test including the header parameters?
I want to make a test on this:
public getAllNodes(): Observable<any> {
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('Authorization', 'someTokenABC');
headers = headers.append('subscriptionId', 'aaa111');
headers = headers.append('organizationId', 'bbb222');
return this.http.get('https://someUrl/getall', {headers: headers, observe: 'response'})
.map(response => {
return response;
})
.catch(this.handleError);
}
This is my test so far:
describe('#getAllNodes', () => {
let injector: TestBed;
let service: MyService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [MyService]
});
injector = getTestBed();
service = injector.get(MyService);
httpMock = injector.get(HttpTestingController);
});
it('should return an Observable<any>', () => {
var dummyNodes = [{
"contentId": "111-222-333",
"title": "some title",
}];
service.getAllNodes().subscribe(nodes => {
expect(nodes.length).toBe(1);
expect(nodes).toEqual(dummyNodes);
});
const req = httpMock.expectOne('https://someUrl/getall');
expect(req.request.method).toBe("GET");
req.flush(dummyNodes);
httpMock.verify();
});
});
In my case I get this error: Expected one matching request for criteria "Match URL: https://someUrl/getall", found none.
But I guess this has something to do with the httpheader. I am not adding this because I don't know how to include them in the test.
Anyone know how I can solve this test?
EDIT:
Or can I do something like this? (nodes is an array of nodes and is filled up when getAllNodes() is called)
describe('#getAllNodes', () => {
let injector: TestBed;
let service: MyService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [MyService]
});
injector = getTestBed();
service = injector.get(MyService);
});
it('should have no nodes at startup', () => {
expect(service.nodes.length).toBe(0);
})
it('should have more than 1 node', () => {
service.getAllNodes();
expect(service.nodes.length).toBeGreaterThan(0);
})
});
But here on the last test it returns 0 hits. Even though service.getAllNodes() should return multiple hits.