2

I need to cover this method with Jasmine in my code

private subject = new Subject<any>();

getMessage(): Observable<any> {
    return this.subject.asObservable();
  }

Here is my constructor

fiscalDocument: FiscalDocumentData;
subscription: Subscription;

constructor(private _myFiscalDocumentsService: MyFiscalDocumentsService) {  
    this.subscription = this._myFiscalDocumentsService.getMessage().subscribe(message => {
      if (message) {
        this.fiscalDocument = message;

      } else {
        this.fiscalDocument = null;
      } 
    });

  }

I've already tried to do that in my test, I have the TestBed.confiugreTestingModule, but I won't post here because I believe that's my problem isn't there

let dummyOb: Observable<any>;

  beforeEach(() => {
    service = TestBed.get(MyFiscalDocumentsService);
    fixture = TestBed.createComponent(MyFiscalDocumentsDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

it('should getMessage', async () => {
    let generalSpy = spyOn(service, 'getMessage' ).and.returnValue(await Promise.resolve(dummyOb));
    expect(generalSpy).toHaveBeenCalled();
 });

The error message: Expected spy getMessage to have been called. EDIT: I got the if condition, now I'm trying the else

3 Answers3

1

It is bad practice use some complex logic in constructor, use ngOnInit instead: Difference between Constructor and ngOnInit

Dmitriy Ivanko
  • 950
  • 8
  • 17
1

By the time you create a spy your constructor has already been called in beforeEach. Try this:

let dummyOb: Observable<any>;

it('should getMessage', async () => {
    let generalSpy = spyOn(service, 'getMessage' ).and.returnValue(await Promise.resolve(dummyOb));
    new MyFiscalDocumentsDetailsComponent(service);
    expect(generalSpy).toHaveBeenCalled();
 });
Stanislav Dontsov
  • 1,591
  • 11
  • 24
  • Thanks, In this exact moment I got a solution in this way `it('should getMessage', async () => { let spy = spyOn(service, 'getMessage').and.callThrough(); component.ngOnInit(); expect(spy).toHaveBeenCalled(); });` Now I'm trying to resolve the else condition – Ravel Sbrissa Okada Sep 23 '19 at 14:12
0

I resolved in this way, an if-else condition wasn't necessary

Component

ngOnInit() {
  this.subscription = this._myFiscalDocumentsService.getMessage().subscribe(message => {
    this.fiscalDocument = message;
  });
}

Spec

it('should getMessage', async () => {
    service.subject.next(dummyMock)
    const spy = spyOn(service, 'getMessage').and.returnValue(of(dummyMock));
    component.ngOnInit();
    expect(component.subscription).toBeDefined();
    expect(spy).toHaveBeenCalled();
});
ssuperczynski
  • 3,190
  • 3
  • 44
  • 61