jasmineemit

How to test emit event on ngSubmit within component subscribe method


On form submit getUsers() is called and if success message is received, the received data is emitted to the parent component.

child html

<form (ngSubmit)="getUsers()">
</form>

child component

getUsers(): void {
    this.userService.getUsers().subscribe(users => {
     if(users.status=="Success"{
      this.listOfUsers = users;
      this.user.emit(this.listOfUsers);
      this.nextTab.emit(true);
     }
    });
  }

i have written the test case to check emit event as follows

it('should emit data on success', () => {
    spyOn(component.user,'emit');
    component.getUsers();
    expect(component.user.emit).toHaveBeenCalled(); // fails as never called what i am doing wrong
  });

Solution

  • You have to make sure that userService.getUsers returns an observable.

    import { of } from 'rxjs';
    ....
    it('should emit data on success', () => {
        // mock userService.getUsers to return { status: 'Success' } to go inside of the if block
        spyOn(userService, 'getUsers').and.returnValue(of({ status: 'Success' }));
        spyOn(component.user,'emit');
        component.getUsers();
        expect(component.user.emit).toHaveBeenCalled(); // fails as never called what i am doing wrong
      });
    

    Edit

    To actually test ngSubmit, I would use triggerEventHandler. You can do some research on it.

    const form = fixture.debugElement.query(By.css('form'));
    // The 2nd argument is what you would like the $event value to be.
    // In our case, null is fine.
    form.triggerEventHandler('ngSubmit', null);
    

    Doing the above will call getUsers.