0
votes

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
  });
1

1 Answers

1
votes

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
  });