Angular 承诺的角度2单元测试

Angular 承诺的角度2单元测试,angular,unit-testing,jasmine,karma-jasmine,Angular,Unit Testing,Jasmine,Karma Jasmine,我通常使用fakeAsync来测试一个返回可观察值的订阅。但在这个难得的场合,我也需要这样做,只是为了一个承诺 这是我的尝试: //Service Stub: const testService = { testMethod: jasmine.createSpy('testMethod').and.callFake(() => new Promise(() => 'test')) }; it('test example',()

我通常使用fakeAsync来测试一个返回可观察值的订阅。但在这个难得的场合,我也需要这样做,只是为了一个承诺

这是我的尝试:

   //Service Stub:

  const testService = {
       testMethod: 
        jasmine.createSpy('testMethod').and.callFake(() => new Promise(() => 'test'))
  };

   it('test example',() => {
      // Arrange
      const response = 'test';
      component.selected = undefined;

      // Act
      component['myMethod']();

      //Assert
      expect(component.selected).toEqual(response);
    });
private myMethod(): void {
  return this.testService.testMethod()
    .then((response: string) => {
      this.selected = response;
    })
    .catch(error => this.logger.error(error, this));
}
这是我的实际代码:

   //Service Stub:

  const testService = {
       testMethod: 
        jasmine.createSpy('testMethod').and.callFake(() => new Promise(() => 'test'))
  };

   it('test example',() => {
      // Arrange
      const response = 'test';
      component.selected = undefined;

      // Act
      component['myMethod']();

      //Assert
      expect(component.selected).toEqual(response);
    });
private myMethod(): void {
  return this.testService.testMethod()
    .then((response: string) => {
      this.selected = response;
    })
    .catch(error => this.logger.error(error, this));
}
基本上,需要知道如何等待“this.testService.testMethod”返回并设置为selected

目前,它没有等待承诺的回报


注意:我已更新了当前尝试。但是expect中仍然没有定义。

您可以尝试调用
勾选()
电话后


(请参阅)

实际上,我不确定是否正确理解了您的问题,但使用async和Wait可能是一个解决方案!请参见下面的示例

要测试的类

import { Router } from '@angular/router';
...

@Injectable({
  providedIn: 'root'
})
export class NavigationService {

  constructor(public router: Router) {
  }

  // Function to test. Note, that the routers navigate function returns a promise.
  navigateToAdminsLandingPage(): void  {
    this.router.navigate(['admin']).then();
  }
测试返回模拟承诺的函数

import ...

describe('NavigationService', () => {

  let testObj: NavigationService;

  // Test setup.
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ]
    });
    testObj = TestBed.get(NavigationHelperService);
  });

  // Testing a promise with async and await.
  it('should navigate to admin landing page', async () => {
    const spy = spyOn(testObj.router, 'navigate').and.returnValue(Promise.resolve(true));

    await testObj.navigateToAdminsLandingPage();

    expect(spy).toHaveBeenCalledTimes(1);
    expect(spy).toHaveBeenCalledWith(['admin']);
  });
});

Tick()给了我同样的结果。如果它是一个订阅一个可观察到的,那么勾号就可以了。看看这里,我更新了我上面的尝试,可能是重复的-我仍然没有定义