mercredi 23 janvier 2019

Angular 6: testing Subject value returned by service

I have a conceptual problem regarding testing a Subject value returned in a service.

Here is the simplified code that reflects the essence of what I have (and which was not written by me):

Service:

@Injectable()
export class MyService {    
  flag: boolean = false;
  private flagSubject = new Subject<boolean>();
  private mySecondService: MySecondService;

  constructor(private mySecondService: MySecondService) {
    ...
    this.flagSubject.next(...);
  }

  isFlag(): Observable<boolean> {
    return this.flagSubject.asObservable();
  };
  ...
}

Test setup:

describe('MyService', () => {
  let myService: MyService;
  let mySecondService: MySecondService;

  beforeEach(async(() => {
    mySecondService = new MySecondService();
    myService = new MyService(mySecondService);
  }));

  it('should return value from observable', (done: DoneFn) => {
    myService.isFlag().subscribe(value => {
      console.log('VALUE:', value); // Never comes here!
      expect(value).toBeFalsy();
      done();
    });
  });
});

I am getting this error:

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

If I change the isFlag() function to this, then it works:

  isFlag(): Observable<boolean> {
    return of(true);
  };

It seems pretty clear that the (expected) behaviour of the flagSubject is the problem.

The question is: do I have to change the code and make the flagSubject a ReplaySubject, for instance? Or do I have to change my testing approach altogether?

Aucun commentaire:

Enregistrer un commentaire