Angular - Unit testing Subject()?

10,784

You should spy on service.serviceMsg and not service, because next() method appears to be on serviceMsg subject.

it('should catch what is emitted', () => {
    const nextSpy = spyOn(service.serviceMsg, 'next');
    service.confirm(ACTION);
    expect(nextSpy).toHaveBeenCalled();
});

EDIT :

You should also change the way you are creating service instance. What you show in your code is applicable only for component instance creation

beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [MessageService]
    });
    service = TestBed.get(MessageService); // get service instance
    httpMock = TestBed.get(HttpTestingController);
});
Share:
10,784
physicsboy
Author by

physicsboy

Updated on June 04, 2022

Comments

  • physicsboy
    physicsboy almost 2 years

    I have a Angular service that simply uses a Subject, but I am unsure of how to write unit tests for it.

    I saw [this thread][1], but I didn't find it terribly helpful.

    I have attempted to mock next() but I am more than a little lost.

  • Admin
    Admin over 5 years
    By doing that you rely on the implementation of Subject, which is not what a unit test should do. You should instead mock it like he tried to do.
  • Buczkowski
    Buczkowski over 5 years
    I believe it is not unit test since it includes things like creating module or injecting. It is true that it will rely on Subject implementation.
  • physicsboy
    physicsboy over 5 years
    I see what you mean. Although I am getting the error: Error: Illegal state: Could not load the summary for directive MessageService.
  • physicsboy
    physicsboy over 5 years
    @trichetriche - Do you have any knowledge of this issue?
  • Amit Chigadani
    Amit Chigadani over 5 years
    You cannot create service instance like fixture = TestBed.createComponent(MessageService); service = fixture.componentInstance;. That is applicable for component only. Instead you should be doing service = TestBed.get(MessageService)
  • physicsboy
    physicsboy over 5 years
    Ah amazing! Thank you for your help @Amit :-)
  • Admin
    Admin over 5 years
    @physicsboy if you want to notify me, it has to be on a question/answer I already commented on, otherwise I don't receive a notification !
  • physicsboy
    physicsboy over 5 years
    @trichetriche - Whoops. Better just giving me your email XD