单元测试模拟拒绝Angular2中的承诺

时间:2017-08-01 15:33:34

标签: angular unit-testing typescript jasmine angularfire2

我正在尝试测试Angular2身份验证服务(authService),特别是模拟AngularFireAuth提供程序,以便通过监视和返回{的值来控制和测试各种身份验证方案{1}}方法,例如AngularFireAuth

以下是我的测试规范的摘录。您可以看到初始signInAnonymously是一个Observable of null - 我们未经过身份验证。然后,authState应尝试匿名进行身份验证(使用authService)。

signInAnonymouslyAngularFire方法返回一个承诺。我希望这被拒绝并且错误被抓住了。

这只是一次情景,但如果我能弄清楚这一点,我可以解决剩下的问题。

auth.service.spec.ts

signInAnonymously

auth.service.ts

import { inject, TestBed } 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 './testing/mock-user';
import { environment } from '../../environments/environment';

let authState: MockUser;
let mockAngularFireAuth: any = {
  auth: jasmine.createSpyObj('auth', [
    'signInAnonymously',
    'signInWithPopup',
    'signOut'
  ]),
  authState: Observable.of(null)
};
let service: AuthService;

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

  beforeEach(inject([ AuthService ], (authService: AuthService) => {
    service = authService;
  }));

  // TODO: Test `authState`  is `null` and throw
  describe('when we can’t authenticate', () => {
    it('should thow', () => {
      mockAngularFireAuth.auth.signInAnonymously.and.returnValue(() => {
        return new Promise((resolve, reject) => {
          reject('fooBar');
        });
      });
    });
  });
});

我得到的错误是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) => { console.log(1, authState); if (authState === null) { console.log(2, authState); this.afAuth.auth.signInAnonymously() .then((authState) => { console.log(3, authState); this.authState = authState; }) .catch((error) => { console.log(4, error.message); throw new Error(error.message); }); } else { console.log(5, authState); this.authState = authState; } }, (error) => { console.log(6, error.message); throw new Error(error.message); }); } } ,位于Cannot read property 'then' of undefined的第21:11行;这正如您所期望的那样auth.service.ts行。

1 个答案:

答案 0 :(得分:0)

AuthService在模拟signInAnonymously之前被实例化。

相反,它可以是

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

    it('...', inject([ AuthService ], (authService: AuthService) => {
      ...