【问题标题】:Angular 2 Unit Test for a promiseAngular 2 单元测试的承诺
【发布时间】:2018-01-09 09:11:16
【问题描述】:

我通常使用 fakeAsync 来测试返回 observable 的订阅。但在这种罕见的情况下,我需要做同样的事情,只是为了一个承诺。

这是我的尝试:

   //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”返回并设置选中。

目前,它不等待承诺返回。

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

【问题讨论】:

标签: angular unit-testing jasmine karma-jasmine


【解决方案1】:

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

要测试的类

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

    【讨论】:

    猜你喜欢
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多