Home > Back-end >  How to test Service with Subject in angular
How to test Service with Subject in angular

Time:04-22

this is my Service.

import { Injectable } from "@angular/core";
import { Subject } from "rxjs";
import { Observable } from "rxjs";
import { filter, map } from "rxjs/operators";

interface i {
  key: any;
  value: any;
}
@Injectable()
export class Srvc {
  private subject: Subject<i>;

  constructor() {
    this.subject = new Subject<i>();
  }

  next(key: any, value?: any) {
    this.subject.next({ key, value });
  }

  sub<T>(key: any): Observable<T> {
    return this.subject.asObservable().pipe(
      filter((event) => {
        return event.key === key;
      }),
      map((event) => <T>event.value)
    );
  }
}

this is my spec file

import { Observable, of, Subject } from "rxjs";
import { Injectable } from "@angular/core";
import { TestBed, inject } from "@angular/core/testing";
import { Srvc } from "./srvc.service"

interface i{
  key: any;
  value: any;
}
fdescribe("Srvc", () => {
  let service: Srvc;

  beforeEach(async () => {
    TestBed.configureTestingModule({
      providers: [
        Srvc,
      ],
    });
  });

  it("should be created", () => {
    service = TestBed.inject(Srvc);
    expect(service).toBeTruthy();
  })

  it('should be subscribed', (() => {
    service = TestBed.inject(Srvc);
    service.next('test', "Hello World");
    service.sub<any>('test').subscribe((message: any) => {
      expect(message).toBe("Hello World")
    })
  }))
})

I am getting "SPEC HAS NO EXPECTATIONS should be subscribed". I am starting with testing in angular. I am reading articles on it but cant figure out what i am doing wrong. Any suggestion will be helpful. Thank you.

CodePudding user response:

it('should be subscribed', ((done) => {
service = TestBed.inject(Srvc);

service.sub<any>('test').subscribe((message: any) => {
  expect(message).toBe("Hello World");
  done();
})
service.next('test', "Hello World");

}))

It is asynchronous so the test suite does not know when the async part is 'done'

  • Related