用Jasmine测试被拒绝的承诺

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用Jasmine测试被拒绝的承诺相关的知识,希望对你有一定的参考价值。

在我使用AngularFire2的Angular2应用程序中,我有一个AuthService尝试匿名使用Firebase进行身份验证。

我试图写一个测试,期望AngularFireAuthsignInAnonymously返回被拒绝的承诺;因为authStatenull而且是一个错误。

我是一个新的Jasmine并且测试一般,但我想我可能需要使用异步测试,但我会陷入困境。

这是一个简化的AuthService

import { Injectable } from '@angular/core';

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class AuthService {
  private authState: firebase.User;

  constructor(private afAuth: AngularFireAuth) { this.init(); }

  private init (): void {
    this.afAuth.authState.subscribe((authState: firebase.User) => {
      if (authState === null) {
        this.afAuth.auth.signInAnonymously()
          .then((authState) => {
            this.authState = authState;
          })
          .catch((error) => {
            throw new Error(error.message);
          });
      } else {
        this.authState = authState;
      }
    }, (error) => {
      throw new Error(error.message);
    });
  }
}

这是我的测试规格:

import { TestBed, inject } from '@angular/core/testing';

import { AngularFireAuth } from 'angularfire2/auth';
import 'rxjs/add/observable/of';
import { Observable } from 'rxjs/Rx';

import { AuthService } from './auth.service';
import { environment } from '../environments/environment';

describe('AuthService', () => {
  const mockAngularFireAuth: any = {
    auth: jasmine.createSpyObj('auth', {
      'signInAnonymously': Promise.resolve('foo'),
      // 'signInWithPopup': Promise.reject(),
      // 'signOut': Promise.reject()
    }),
    authState: Observable.of(null)
  };

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        { provide: AngularFireAuth, useValue: mockAngularFireAuth },
        { provide: AuthService, useClass: AuthService }
      ]
    });
  });

  it('should be created', inject([ AuthService ], (service: AuthService) => {
    expect(service).toBeTruthy();
  }));

  //
  //
  //
  //
  //

  describe('when we can’t authenticate', () => {
    beforeEach(() => {
      mockAngularFireAuth.auth.signInAnonymously.and.returnValue(Promise.reject('bar'));
    });

    it('should thow', inject([ AuthService ], (service: AuthService) => {
      expect(mockAngularFireAuth.auth.signInAnonymously).toThrow();
    }));
  });

  //
  //
  //
  //
  //

});

谢谢您的帮助!

答案

事实证明我正在嘲笑mockAngularFireAuth。我需要拒绝mockAngularFireAuth.auth signInAnonymously()的承诺错误并期望它被抓住,一个la:

import { TestBed, async, inject } from '@angular/core/testing';

import { AngularFireAuth } from 'angularfire2/auth';
import 'rxjs/add/observable/of';
import { Observable } from 'rxjs/Rx';

import { AuthService } from './auth.service';
import { MockUser} from './mock-user';
import { environment } from '../environments/environment';

describe('AuthService', () => {
  // An anonymous user
  const authState: MockUser = {
    displayName: null,
    isAnonymous: true,
    uid: '17WvU2Vj58SnTz8v7EqyYYb0WRc2'
  };

  const mockAngularFireAuth: any = {
    auth: jasmine.createSpyObj('auth', {
      'signInAnonymously': Promise.reject({
        code: 'auth/operation-not-allowed'
      }),
      // 'signInWithPopup': Promise.reject(),
      // 'signOut': Promise.reject()
    }),
    authState: Observable.of(authState)
  };

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        { provide: AngularFireAuth, useValue: mockAngularFireAuth },
        { provide: AuthService, useClass: AuthService }
      ]
    });
  });

  it('should be created', inject([ AuthService ], (service: AuthService) => {
    expect(service).toBeTruthy();
  }));

  describe('can authenticate anonymously', () => {
    describe('AngularFireAuth.auth.signInAnonymously()', () => {
      it('should return a resolved promise', () => {
        mockAngularFireAuth.auth.signInAnonymously()
          .then((data: MockUser) => {
            expect(data).toEqual(authState);
          });
      });
    });
  });

  describe('can’t authenticate anonymously', () => {
    describe('AngularFireAuth.auth.signInAnonymously()', () => {
      it('should return a rejected promise', () => {
        mockAngularFireAuth.auth.signInAnonymously()
          .catch((error: { code: string }) => {
            expect(error.code).toEqual('auth/operation-not-allowed');
          });
      });
    });
  });
  …
});
另一答案

我通过执行以下操作解决了这个问题:

    describe('should reject promise', () => {

        let resolved: boolean;
        let rejected: boolean;
        let _e: any;

        beforeEach(function (done) {
            resolved = false;
            rejected = false;
            // ensure conditions here are such that myFn() should return a rejected promise
            service.myFn().then(() => {
                resolved = true;
                done();
            }).catch((e) => {
                rejected = true;
                _e = e;
                done();
            });
        })

        it('should reject', () => {
            expect(resolved).toEqual(false);
            expect(rejected).toEqual(true);
            expect(_e.name).toEqual("MyCustomErrorName");
        });
    });

以上是关于用Jasmine测试被拒绝的承诺的主要内容,如果未能解决你的问题,请参考以下文章

在 Nodejs 中使用 Jasmine 测试 promise 是不是被解决或拒绝

如何使用 Jest 正确测试被拒绝的承诺?

如何模拟在 AngularJS Jasmine 单元测试中返回承诺的服务?

CordovaError:承诺被非错误拒绝:错误代码 65

如何在 Mocha 测试中调试“错误:无理由或错误理由拒绝承诺”?

使用 Angular Promise 进行 Jasmine 测试无法使用 TypeScript 解决