Test for rejected promise with Jasmine

前端 未结 2 1270
孤城傲影
孤城傲影 2021-01-23 00:50

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

I am trying to write a test that ex

2条回答
  •  忘掉有多难
    2021-01-23 01:31

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

提交回复
热议问题