18

我正在尝试使用 AngularFire 2 auth 为示例 Angular 2 应用程序设置单元测试,该组件非常简单:

import { Component } from '@angular/core';
import { AngularFire, AuthProviders } from 'angularfire2';

@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
  isLoggedIn: boolean;

  constructor(public af: AngularFire) {
    this.af.auth.subscribe(auth => {
      if (auth) {
        this.isLoggedIn = true;
      } else {
        this.isLoggedIn = false;
      }
    });
  }

  loginWithFacebook() {
    this.af.auth.login({
      provider: AuthProviders.Facebook
    });
  }

  logout() {
    this.af.auth.logout();
  }
}

我所做的只是在 AngularFire 中封装loginandlogout方法,所以我正在考虑使用模拟来检查方法是否被调用,但我不确定从哪里开始,我尝试在我的规范文件中执行以下操作:

import { provide } from '@angular/core';
import { AngularFire } from 'angularfire2';
import {
  beforeEach, beforeEachProviders,
  describe, xdescribe,
  expect, it, xit,
  async, inject
} from '@angular/core/testing';
import { AppComponent } from './app.component';

spyOn(AngularFire, 'auth');

beforeEachProviders(() => [
  AppComponent,
  AngularFire
]);

describe('App Component', () => {
  it('should create the app',
    inject([AppComponent], (app: AppComponent) => {
      expect(app).toBeTruthy();
    })
  );

  it('should log user in',
    inject([AppComponent], (app: AppComponent) => {
      expect(app.fb.auth.login).toHaveBeenCalled();
    })
  );

  it('should log user out',
    inject([AppComponent], (app: AppComponent) => {
      expect(app.fb.auth.logout).toHaveBeenCalled();
    })
  );
});

但是我不确定如何模拟loginandlogout方法,因为它们是auth属性的一部分,有没有办法模拟auth以及返回loginlogout方法?

4

3 回答 3

18

在这个片段中:

beforeEach(() => addProviders([
  AppComponent,
  AngularFire
]);

您设置(或覆盖)将在测试中使用的提供程序。

话虽如此,您可以创建一个不同的类,如果您愿意,可以创建一个模拟,并使用该{ provide: originalClass, useClass: fakeClass }符号提供它而不是AngularFire实际的类。

像这样的东西:

class AngularFireAuthMock extends AngularFireAuth {           // added this class
  public login() { ... }
  public logout() { ... }
}

class AngularFireMock extends AngularFire {                   // added this class
  public auth: AngularFireAuthMock;
}

beforeEach(() => addProviders([
  AppComponent,
  { provide: AngularFire, useClass: AngularFireMock }         // changed this line
]);

并且AngularFire您的测试中的 s 将是AngularFireMocks。

于 2016-06-26T22:52:51.847 回答
1

希望这不是主题,但我找到了如何模拟 FirebaseDatabase 的最简单的解决方案。

var object = function() {
      var obj = { valueChanges() {
            return of({data:'data'});     
        }
      }
      return obj;
    }

providers: [..., { provide : AngularFireDatabase,
        useValue: {object : object }} ]

而不是 data:'data' 你可以模拟你需要的任何数据。可以根据需要修改功能。

于 2019-03-24T18:16:11.840 回答
0

与@jan 类似,我使用一些实用函数做了一个模拟:

import {AngularFireAuth} from '@angular/fire/auth';
import {AngularFireDatabase} from '@angular/fire/database';
import {auth} from 'firebase/app';

import { Observable, of, Subscription } from 'rxjs';

/**
 * Mocks the Firebase auth by automatically logging in.
 */
export const AngularFireAuthMock = jasmine.createSpy('signInWithEmailAndPassword')
      .and.returnValue(Promise.resolve({uid: 'fakeuser'}));

/**
 * Mocks an AngularFireDatabase that always returns the given data for any path.
 */
export function mockAngularFireDatabase(data): AngularFireDatabase {
  return {
    object: (path: string): any => {
      return {
        valueChanges() {
          return of(data);
        }
      }
    }
  } as AngularFireDatabase;
}

然后你可以像这样在你的规范中使用它们:

 beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ TweakComponent ],
      imports: [ MatDialogModule, RouterTestingModule ],
      providers: [
       { provide: MAT_DIALOG_DATA, useValue: {} },
       { provide: AngularFireDatabase, useValue: mockAngularFireDatabase({testdata:'hi'})},
       { provide: AngularFireAuth, useValue: AngularFireAuthMock}
     ],
    })
    .compileComponents();
  });
于 2020-11-04T00:16:14.443 回答