简体   繁体   中英

Angular unit test, how to test a subject as observable

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.'

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

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();
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM