【问题标题】:How to test callback with Jasmine in Angular如何在 Angular 中使用 Jasmine 测试回调
【发布时间】:2021-06-27 11:37:03
【问题描述】:

我正在尝试测试 SignalR HubConnection 的 onclose 回调,但我找不到如何触发 onclose 回调。

这是我要测试的:

@Injectable({
  providedIn: 'root'
})
export class CloseConnectionHandlerService {
  constructor(
    private signalRService: SignalRService) {
  }

  public initialize(): void {
    this.signalRService.hubConnection?.onclose((error: any) => {
      if (error) {
        console.error(error);
      }
    });
  }
}

我正在尝试使用以下代码:

describe('CloseConnectionHandlerService', () => {
  let service: CloseConnectionHandlerService;
  let signalRServiceSpy: jasmine.SpyObj<SignalRService>;
  
  beforeEach(() => {
    signalRServiceSpy = {
      ...jasmine.createSpyObj('SignalRService', ['']),
    } as jasmine.SpyObj<SignalRService>;

    TestBed.configureTestingModule({
      providers: [
        {provide: SignalRService, useValue: signalRServiceSpy},
      ]
    });

    service = TestBed.inject(CloseConnectionHandlerService);
  });
  
  describe('#initialize', () => {
    it('should log error to the console', () => {
      // Arrange
      spyOn(console, 'error');

      const hubConnectionStartSpy = jasmine.createSpyObj(HubConnection, ['onclose']);
      hubConnectionStartSpy.onclose.and.callFake(() => 'Error!');
      signalRServiceSpy.hubConnection = hubConnectionStartSpy

      // Act
      service.initialize();

      // Assert
      expect(console.error).toHaveBeenCalled();
    });
  });
});

当我运行它时,我得到了 console.error 没有被调用的错误。有人知道我该如何测试吗?

【问题讨论】:

    标签: javascript angular unit-testing callback jasmine


    【解决方案1】:

    this.signalRService.hubConnection?.onclose() 方法接受一个回调参数。所以.callFake() 方法创建的假实现将覆盖原始实现,您可以在测试用例中接收原始回调函数。然后,手动使用虚假错误调用它。

    例如

    const hubConnectionStartSpy = jasmine.createSpyObj('HubConnection', ['onclose']);
    
    hubConnectionStartSpy.onclose.and.callFake((callback) =>
      callback('Error!'); // You will get the original callback here, invoke it with fake error.
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 2021-11-25
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2018-11-15
      相关资源
      最近更新 更多