Home > Mobile >  Angular unit test, how to test a subject as observable
Angular unit test, how to test a subject as observable

Time:02-21

I am trying to test a subject as observable, but it is not working as expected
For simplistic I have removed extra logic inside getService2Test subscribe

Below is my function in service class

getTest():Observable<string>{
   let subject = new Subject<string>();
   service2.getService2Test().subscribe(result=>{
        subject.next(result.success);   // result.success = "testing"
        subject.complete();
   });
   
   return subject.asObservable();
}

Below is my test case

it('Testing getTest()',()=>{
   spyOn(service2,'getService2Test').and.returnValue(of("success"));
   service.getTest().subscribe((result)=>{
        expect(result).toEqual("testing");        // never gets invoked in testing
        console.log("Output result: " result);    // not able to see any message
   });
});

The code inside subscribe never executed. I am also getting a warn message of '... has no expectations.'

CodePudding user response:

Your test case doesn't wait for your subscribe and is instantly finished. To fix this implement the resolve callback like this:

it('Testing getTest()', done => {
   spyOn(service2,'getService2Test').and.returnValue(of("success"));
   service.getTest().subscribe((result)=>{
        // verify results
        done();
   });
});

Jest documentation

CodePudding user response:

Thanks Felix, I have tested and below code works

it('Testing getTest()', done => {
   spyOn(service2,'getService2Test').and.returnValue(of("success").pipe(delay(0)));
   service.getTest().subscribe((result)=>{
        console.log(result);   // Prints my results
        done();
   });
});
  • Related