如何在组件订阅方法中测试 ngSubmit 上的发射事件

How to test emit event on ngSubmit within component subscribe method

在表单提交时调用 getUsers(),如果收到成功消息,收到的数据将发送到 parent 组件。

child html

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

child分量

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

我已经编写了测试用例来检查发射事件,如下所示

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

你必须确保 userService.getUsers returns 是可观察的。

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