如何在Jasmine中运行Promise测试

时间:2016-08-12 00:58:48

标签: jasmine promise karma-jasmine

我正在尝试在我注入我的应用程序的单独库中测试一个承诺。

function myFunc(input) {
        return new Promise(function(resolve, reject) {
             ···
            resolve(value); // success
            ···
            reject(error); // failure
        });
    };

这是我的函数,它返回一个Promise。

我非常希望像茉莉一样运行测试

describe('Service: myService', function () {
    var $log;

beforeEach(inject(function (_$log_) {
    $log = _$log_;
}));

it('should get results', function () {
    $log.log("start test");

    var self = this;
    myFunc(input).then(function(response) {
            $log.log("success");
            expect(response).toBe("response");
            done();
    }).catch(function(error) {
            $log.log("fail");
            self.fail(error);
            done();
    });
    $log.log("end test");
});
});

我的测试通过(不是预期的)。我的日志中唯一的东西是[开始测试]和[结束测试],好像承诺完全被忽略了。 由于我没有使用$ q作为承诺,大多数茉莉花提示角度似乎没有帮助。

关于如何进入'那么'的任何想法?

由于

1 个答案:

答案 0 :(得分:0)

要测试的TypeScipt代码(Angular 8)

import { Injectable } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';
import { environment } from 'environments/environment';
import { LoggedInUserHelperService } from 'shared/helper/logged-in-user-helper.service';

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

  constructor(public keycloakService: KeycloakService) {
  }

  initApplication(): Promise<any> {
    return new Promise<any>(
        async (resolve: any, reject: any): Promise<any> => {
          await this.initKeycloak()
              .then(() => keyCloakInitialized = true)
              .catch((error: Error) => {
                console.error(`Couldn\'t initialize Keycloak Service. (Error: ${error})`);
                reject(error);
                return;
              });

          resolve();
        }
    );
  }

  private async initKeycloak(): Promise<any> {
    return this.keycloakService.init({
      config: environment.keycloak,
      initOptions: {
        onLoad: 'login-required',
        checkLoginIframe: false,
        promiseType: 'legacy'
      },
      enableBearerInterceptor: true,
      bearerExcludedUrls: ['/assets']
    });
  }
}

测试

import { TestBed } from '@angular/core/testing';
import { AppInitializationService } from 'app/app-initialization.service';
import { KeycloakService } from 'keycloak-angular';

describe('AppInitializationService', () => {

  let testObj: AppInitializationService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        KeycloakService
      ]
    });
    testObj = TestBed.get(AppInitializationService);
  });

  it('should call keycloak service init', async () => {
    const spy = spyOn(testObj.keycloakService, 'init').and.returnValue(Promise.resolve(true));

    await testObj.initApplication();

    expect(spy).toHaveBeenCalledTimes(1);
    expect(spy).toHaveBeenCalledWith({
      config: environment.keycloak,
      initOptions: {
        onLoad: 'login-required',
        checkLoginIframe: false,
        promiseType: 'legacy'
      },
      enableBearerInterceptor: true,
      bearerExcludedUrls: ['/assets']
    });
  });


  it('should log error on failed keycloak initialization', async () => {
    const errorMsg = 'error-msg';
    const spy1 = spyOn(testObj.keycloakService, 'init').and.callFake(
        () => Promise.reject(errorMsg));
     const spy2 = spyOn(console, 'error');

    await testObj.initApplication().catch(() => { return; });

    expect(spy1).toHaveBeenCalledTimes(1);
    expect(spy2).toHaveBeenCalledTimes(1);
    expect(spy2).toHaveBeenCalledWith(`Couldn\'t initialize Keycloak Service. (Error: ${errorMsg})`);
  });
});