Angular 2 单元测试的承诺

问题描述 投票:0回答:2

我通常使用 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));
}

基本上,需要知道如何等待“this.testService.testMethod”返回并设置选择。

目前还没有等待promise返回。

注意:我已经更新了我当前的尝试。但在预期中仍然未定义。

angular unit-testing jasmine karma-jasmine
2个回答
0
投票

实际上我不确定我是否正确理解你的问题,但使用 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']);
  });
});

-2
投票

您可以尝试拨打

tick()
通话后

(参见 https://angular.io/guide/testing#the-fakeasync-function

© www.soinside.com 2019 - 2024. All rights reserved.