订阅 returns 未定义且始终失败的组件方法的 Jasmine 单元案例

Jasmine Unit Case for component method which has subscription returns undefined and always fails

我的组件有以下方法:

get(): void {
  this.service.get().subscribe((res) => {
    this.response = res;
  });
}

我有以下测试用例:

it('should get content ', () => {
  const currentObject = {};

  spyOn(service, 'get').and.returnValue(of(currentObject));

  component.get();

  fixture.detectChanges();
  expect(component.response).toEqual(currentObject);

});

结果总是:

Expected undefined to equal Object({ }).

这里有很多类似的问题,但出于某些原因 none 这些对我有用。

我认为这可能是由于代码的异步性质,其中 .subscribe 发生在您的 expect 之后。

试试这个调试:

get(): void {
  this.service.get().subscribe((res) => {
    // !! add this log and ensure you see it first
    console.log('[get] This should happen first');
    this.response = res;
  });
}

// Test
it('should get content ', () => {
  const currentObject = {};

  spyOn(service, 'get').and.returnValue(of(currentObject));

  component.get();

  fixture.detectChanges();
  // !! add this log and ensure you see it last
  console.log('[test] This should happen last');
  expect(component.response).toEqual(currentObject);

});

确保在 This should happen last 之前看到 This should happen first

我认为修复它的潜在方法可能是使用 fakeAsync/tick

// wrap callback function in fakeAsync
it('should get content ', fakeAsync(() => {
  const currentObject = {};

  spyOn(service, 'get').and.returnValue(of(currentObject));

  component.get();

  fixture.detectChanges();
  // call tick() here to ensure the asynchronous subscribe runs before the expect
  tick();
  expect(component.response).toEqual(currentObject);

}));