2

I want to test a service which has a method which returns an observable, but I keep getting this error when running a expect inside subscribe

Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)

I tried to increase the timeout interval for Jasmine, but this didn't work. Here is my code:

user.service.ts:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  subject: Subject<string> = new Subject<string>();

  constructor() { }

  sendUserNotification(message: string): void {
    this.subject.next(message);
  }

  getUserNotification(): Observable<string> {
      return this.subject.asObservable();
  }

}

user.service.spec.ts:

import { TestBed } from '@angular/core/testing';
import { UserService } from './user.service';

describe('UserService', () => {
  let service: UserService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(UserService);
  });

  it('should be able to set and get the registered user', (done) => {
    service.sendUserNotification('testNotification');
    service.getUserNotification().subscribe((notification: string): void => {
      expect(notification).toEqual('testNotification1');   //  This is causing the error
      done();
    });
  });
});

Please advise what could be wrong. Thanks!

1 Answer 1

2

Your issue is that you are doing the call in the wrong order.

Because you are dispatching the event and then subscribing, when in fact, you should subscribe first and then dispatch the event.

On resume, in your spec file you need to do:

import { TestBed } from '@angular/core/testing';
import { UserService } from './user.service';

describe('UserService', () => {
  let service: UserService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(UserService);
  });

  it('should be able to set and get the registered user', (done) => {
    service.getUserNotification().subscribe((notification) => {
      expect(notification).toEqual('testNotification1');
      done();
    });
    service.sendUserNotification('testNotification');
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Your welcome. Also, another improvement that you can do is instead of having the method getUserNotification() returning this.subject.asObservable(); every time you want to subscribe to the subject, you can create a public property like this one: userNotification$ : Observable< string > = this.subject.asObservable(), there you will call only once to this.subject.asObservable();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.