I was struggling to test nested with observables and testing emits.
I was looking at a few posts on medium, however it didn't cut it when I needed it to work.
A simple fix that I found on stack overflow helped a lot.
I didn't even use a textcomponentfixture class. It was a bit too complicated.
Following the guide on Stackoverflow and using SpyOn emits we can achieve a good test.
So the first thing you want to do is setup the test and a SpyObj inside your beforeAll
method in your test suite.
let spyEmit: jasmine.SpyObj<EventEmitter<Project>>
beforeAll(() => {
spyEmit = jasmine.createSpyObj('EventEmitter', ['emit']);
});
Make sure you have the spyEmit in your describe.
Then you have to make sure you set the default EventEmitter in your beforeEach
So before you run your fixture.detectChanges();
make sure you set you fake EventEmitter.
...
fixture = TestBed.createComponent(ProjectFormComponent);
component = fixture.componentInstance;
component.projectDataReturn = spyEmit;
...
This is so that it reflects this code in the parent component:
...
@Output() projectDataReturn = new EventEmitter<Project>();
...
Now when you run your code can use a fake spy
...
spyEmit.emit.and.callFake((project) => {
expect(project).toEqual({...fakeProject, id: "old1"});
});
...
This allows you to capture the call and check it for each test units.
Of course you can run expect(spyEmit.emit).toHaveBeenCalled();
to check if the fake method has been called.
Top comments (0)