2017-09-16 6 views
-1

AngularFire2를 사용하는 Angular2 앱에는 Firebase로 익명 인증을 시도하는 AuthService이 있습니다.재스민 Observable에 가입하지 못했음을 테스트했습니다.

AngularFireAuthauthState에 대한 구독이 실패 (관찰 가능한 시퀀스의 예외적 종료)하고 오류가 발생할 것으로 예상되는 테스트를 작성하려고합니다.

나는 무엇이 similar question 인 것처럼 보였습니다. 그러나 여기에서는 "관찰 가능한 시퀀스의 예외적 종료"를 테스트합니다. 제 3 자 제공 업체 인 Firebase이 다운되었을 때.

이것은 거절 한 약속을 테스트하고있는 다른 관련 (관련) 질문과 별개입니다. 여기

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(service).toThrow(); 
    })); 
    }); 

    // 
    // 
    // 
    // 
    // 

}); 

난 안이 가능하다조차 확실, 또는 필요 해요 -이 일 것 같은 아주 예외적 인 경우. 테스트를 시작할 예정이라면 가능한 한 포괄적이고 방수성이 있어야합니다. 도와 줘서 고마워!

+0

가능한 중복 https://stackoverflow.com/questions/46252850/test- : 나는 onError 기능에 mockAngularFireAuth.authState에 가입 할 때 나는, 라 오류를 기대한다 for-rejected-promise-with-jasmine) – jonrsharpe

+0

감사합니다. @jonrsharpe 그러나 이것은 속는 것이 아닙니다. 이 Q는'AngularFireAuth'의'authState'에 가입하려 할 때 '관찰 가능한 시퀀스의 예외적 인 종료'가있을 때 에러가 발생할 것으로 예상되는 테스트 스펙을 쓰는 방법을 묻습니다. 건배 –

+0

@jonrsharpe 당신은 두 가지 질문에 모두 찬성 했습니까? 그것들은 중복되지 않으며 문제를 분명히 설명한다고 느낍니다. 원하는 결과는 무엇이며 간결한 코드 예제가 있습니다. 질문을 어떻게 개선 할 수 있는지 제안 해 주시겠습니까? 당신을 도울 수 있습니까? –

답변

0

mockAngularFireAuthauthState을 간첩하고 오류를 발생시키는 Observable을 반환해야했습니다.

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('catastrophically fails',() => { 
    beforeEach(() => { 
     const spy = spyOn(mockAngularFireAuth, 'authState'); 

     spy.and.returnValue(Observable.throw(new Error('Catastrophe'))); 
    }); 

    describe('AngularFireAuth.authState',() => { 
     it('should invoke it’s onError function',() => { 
     mockAngularFireAuth.authState.subscribe(null, 
      (error: Error) => { 
      expect(error).toEqual(new Error('Catastrophe')); 
      }); 
     }); 
    }); 
    }); 
    … 
}); 
([재스민과 거부의 약속에 대한 테스트]의