2017-09-16 4 views
0

AngularFire2를 사용하는 Angular2 앱에는 Firebase로 익명으로 인증을 시도하는 AuthService이 있습니다.Jasmine으로 거부 된 테스트를위한 테스트

AngularFireAuthsignInAnonymously이 거부 된 약속을 반환 할 것으로 예상되는 테스트를 작성하려고합니다. authStatenull이고 오류가 발생합니다.

저는 재스민과 테스트 전반에 익숙하지만 비동기 테스트를 사용해야 할 수도 있다고 생각합니다. 여기 내 테스트 사양하는

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

    // 
    // 
    // 
    // 
    // 

}); 

여러분의 도움에 감사드립니다

여기에 단순화 된 AuthService입니다!

+0

왜 당신이 테스트를 작성을 모의? 테스트중인 코드는 무엇을하고 있습니까? – jonrsharpe

+0

안녕하세요 @ jonrsharpe, 나는 AngularFireAuth의'signInAnonymously'을 조롱하고 있습니다. 그렇지 않으면 테스트가 실행될 때마다 Firebase에 실제 호출을합니다. 나는 이런 종류의 제 3 자 제공자를 조롱하기로되어 있다고 믿게되었습니다. –

+0

네,하지만 그 모의 것이 당신의 검사가 운동하는 것 같은 유일한 것입니다. – jonrsharpe

답변

0

나는 mockAngularFireAuth을 정확하게 조롱하고 있었다. 나는 오류와 mockAngularFireAuth.auth signInAnonymously()의 약속을 거부 필요하고 그것은, 라 잡힐 것으로 예상 :

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'); 
      }); 
     }); 
    }); 
    }); 
    … 
}); 
+0

약속이 거부 될 것으로 예상되면 약속이 이행되었는지 확인하지 못합니다. 그리고 또 다른 방법. –

0

나는 수행하여이 문제를 해결 다음

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"); 
     }); 
    });