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);
});
Author by
physicsboy
Updated on June 04, 2022Comments
-
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 over 5 yearsBy 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 over 5 yearsI 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 over 5 yearsI see what you mean. Although I am getting the error:
Error: Illegal state: Could not load the summary for directive MessageService.
-
physicsboy over 5 years@trichetriche - Do you have any knowledge of this issue?
-
Amit Chigadani over 5 yearsYou cannot create
service
instance likefixture = TestBed.createComponent(MessageService); service = fixture.componentInstance;
. That is applicable for component only. Instead you should be doingservice = TestBed.get(MessageService)
-
physicsboy over 5 yearsAh amazing! Thank you for your help @Amit :-)
-
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 over 5 years@trichetriche - Whoops. Better just giving me your email XD