Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Unit testing Subject()?

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.

like image 731
physicsboy Avatar asked Mar 17 '26 07:03

physicsboy


1 Answers

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);
});
like image 96
Amit Chigadani Avatar answered Mar 18 '26 20:03

Amit Chigadani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!