【问题标题】:Test for rejected promise with Jasmine用 Jasmine 测试被拒绝的承诺
【发布时间】:2018-02-25 10:19:03
【问题描述】:

在我使用 AngularFire2 的 Angular2 应用程序中,我有一个 AuthService,它尝试使用 Firebase 进行匿名身份验证。

我正在尝试编写一个测试,期望AngularFireAuth 的signInAnonymously 返回一个被拒绝的承诺; authState 为 null 并抛出错误。

我是 Jasmine 和一般测试的新手,但我认为我可能需要使用异步测试,但我陷入了困境。

这是一个简化的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(mockAngularFireAuth.auth.signInAnonymously).toThrow();
    }));
  });

  //
  //
  //
  //
  //

});

感谢您的帮助!

【问题讨论】:

  • 你为什么要为模拟写测试?被测代码应该做什么?
  • 嗨@jonrsharpe,我在嘲笑AngularFireAuth 的signInAnonymously,否则每次运行测试时都会对Firebase 进行实际调用。我被引导相信我应该嘲笑这些第 3 方提供商?
  • 是的,但模拟是你的测试似乎唯一在锻炼的东西。
  • 那只是因为我还没有编写 AuthService 的其余部分或为这些未来方法编写任何更多测试 ;-) 我认为我很乐意编写这些测试,以便保持简洁我已经仅包括我实际需要帮助的测试。干杯

标签: javascript angular jasmine karma-jasmine angularfire2


【解决方案1】:

事实证明我正确地嘲笑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');
          });
      });
    });
  });
  …
});

【讨论】:

  • 当您预计承诺会被拒绝时,您会错过检查承诺是否已兑现。反之亦然。
【解决方案2】:

我通过执行以下操作解决了这个问题:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-28
    • 2018-11-22
    • 2015-06-04
    • 2022-01-23
    • 2018-05-09
    • 2017-03-28
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多