用Jasmine测试被拒绝的承诺

用Jasmine测试被拒绝的承诺

本文介绍了用Jasmine测试被拒绝的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my Angular2 app which uses AngularFire2, I have an AuthService which tries to authenticate anonymously with Firebase.

我正在尝试编写一个测试,希望 AngularFireAuth signInAnonymously 返回被拒绝的承诺;对于 authState null 并抛出错误。

I am trying to write a test that expects AngularFireAuth's signInAnonymously to return a rejected promise; for authState to be null and an error to be thrown.

我是Jasmine的新手,一般都在测试,但我想我可能需要使用异步测试但是我已经陷入困境了。

I an new to Jasmine and testing in general but I think I may need to be using asynchronous tests but I'm getting quite stuck.

这是一个简化的 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:

It turns out I was mocking mockAngularFireAuth correctly. I needed to reject mockAngularFireAuth.auth signInAnonymously()'s promise with an error and expect it to be caught, a 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');
          });
      });
    });
  });
  …
});

这篇关于用Jasmine测试被拒绝的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 13:20