Test for rejected promise with Jasmine

ⅰ亾dé卋堺 提交于 2019-12-02 12:43:56

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

I solved this problem by doing the following:

    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");
        });
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!