本文介绍了对使用 AngularFireAuth 和 Mocking authState 的服务进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在兜圈子,试图对依赖于 AngularFireAuth 的服务 (AuthService) 进行单元测试.

I have been going round in circles trying to unit test a Service (AuthService) that depends upon AngularFireAuth.

我正在尝试寻找一种方法来模拟或劫持 Observable AngularFireAuth.authState,而不是实际与 Firebase 对话的服务.

I am trying to find a way to mock, or highjack the Observable AngularFireAuth.authState instead of the Service actually talking to Firebase.

这是我的测试规范:

import { inject, TestBed } from '@angular/core/testing';

import { AngularFireModule } from 'angularfire2';
import { AngularFireAuth, AngularFireAuthModule } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import 'rxjs/add/observable/of';
// import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Rx';

import { AuthService } from './auth.service';
import { environment } from '../../environments/environment';

const authState: firebase.User = null;
const mockAngularFireAuth: any = { authState: Observable.of(authState) };

describe('AuthService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [AngularFireModule.initializeApp(environment.firebaseAppConfig)],
      providers: [
        { provider: AngularFireAuth, useValue: mockAngularFireAuth },
        AuthService
      ]
    });
  });

  it('should be defined', inject([ AuthService ], (service: AuthService) => {
    expect(service).toBeDefined();
  }));

  it('.authState should be null', inject([ AuthService ], (service: AuthService) => {
    expect(service.authState).toBe(null);
  }));
});

这是我的(简化的)服务:

And here is my (simplified) Service:

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) => {
      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);
    });
  }

  public get currentUser(): firebase.User {
    return this.authState ? this.authState : undefined;
  }

  public get currentUserObservable(): Observable<firebase.User> {
    return this.afAuth.authState;
  }

  public get currentUid(): string {
    return this.authState ? this.authState.uid : undefined;
  }

  public get isAnonymous(): boolean {
    return this.authState ? this.authState.isAnonymous : false;
  }

  public get isAuthenticated(): boolean {
    return !!this.authState;
  }

  public logout(): void {
    this.afAuth.auth.signOut();
  }
}

我收到错误属性authState"是私有的,只能在AuthService"类中访问.

当然可以,但我不想实际访问它——我想模拟或劫持它,以便我可以在我的测试规范中控制它的值.我相信我在这里的代码偏离了方向.

Of course it is, but I don't want to actually access it — I want to mock or highjack it so I can control it's value from within my test spec. I believe I am way off-course with my code here.

请注意,我使用的是 AngularFire2 的 ^4 版本,并且引入了重大更改;记录在这里:https://github.com/angular/angularfire2/blob/master/docs/version-4-upgrade.md

Please note I am using version ^4 of AngularFire2 and there were breaking changes introduced; documented here: https://github.com/angular/angularfire2/blob/master/docs/version-4-upgrade.md

推荐答案

封装的成员可以被反射.

Encapsulated members can be reflected.

艰难的道路:

expect(Reflect.get(service, 'authState')).toBe(null);

简单的方法:

expect(service['authState']).toBe(null);
expect((service as any).authState).toBe(null);

这篇关于对使用 AngularFireAuth 和 Mocking authState 的服务进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-25 15:35