I have one service which is returning the forkjoin of multiple http calls. I wanted to test this scenario.
class CommentService{
addComments(){
let ob1 = Observable.of({});
let ob2 = Observable.of({});
if(any condition)
ob1 = {this.http.post('/url/1')};
if(any condition)
ob2 = {this.http.post('/url/2'};
return Observable.forkJoin(ob1,ob2)
}
}
Above is my service class. How can i mock the http calls.
describe("CommentService", () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule, HttpClientTestingModule],
providers: [CommentService]
});
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
});
it('addComments() call with normal and gate', inject([CommentService], (service: CommentService) => {
let cmts = service.addComments();
const reqGateComment = httpTestingController.expectOne('/url/1');
expect(reqGateComment.request.method).toEqual('POST');
const reqFactComment = httpTestingController.expectOne('/url/2');
expect(reqFactComment.request.method).toEqual('POST');
reqGateComment.flush({});
reqFactComment.flush({});
httpTestingController.verify();
cmts.subscribe(results=>{
expect(results.length).toEqual(2);
});
}));
});
I am getting the below test fail. CommentService addFactsAndComments() call with normal and gate
Error: Expected one matching request for criteria "Match URL:
'/url/1", found none.
I had a similar problem and I solved it using fakeAsync.
it('addComments() call with normal and gate', fakeAsync( inject([CommentService], (service: CommentService) => {
service.addComments().subscribe(results=>{
expect(results.length).toEqual(2);
});
const reqGateComment = httpTestingController.expectOne('/url/1');
expect(reqGateComment.request.method).toEqual('POST');
reqGateComment.flush({});
tick(10000);
const reqFactComment = httpTestingController.expectOne('/url/2');
expect(reqFactComment.request.method).toEqual('POST');
reqFactComment.flush({});
httpTestingController.verify();
})));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With