DEV Community

Bhavesh Ramburn
Bhavesh Ramburn

Posted on

Angular Testing with @Input

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']);
        });
Enter fullscreen mode Exit fullscreen mode

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;
...
Enter fullscreen mode Exit fullscreen mode

This is so that it reflects this code in the parent component:

...
 @Output() projectDataReturn = new EventEmitter<Project>();
 ...
Enter fullscreen mode Exit fullscreen mode

Now when you run your code can use a fake spy

  ...
  spyEmit.emit.and.callFake((project) => {
                expect(project).toEqual({...fakeProject, id: "old1"});
            });
   ...         
Enter fullscreen mode Exit fullscreen mode

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)