How to mock AngularFire 2 service in unit test?
Asked Answered
A

3

18

I'm trying to set up unit tests for a sample Angular 2 app using AngularFire 2 auth, the component is fairly simple:

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

All I'm doing is wrapping around the login and logout methods in AngularFire so I was thinking about using a mock to check if the methods were called but I'm not sure where to start, I tried doing the following in my spec file:

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

However I'm not sure how to mock the login and logout methods since they're part of the auth property, is there a way to mock auth and also the returning login and logout methods?

Arredondo answered 26/6, 2016 at 20:36 Comment(1)
The interested reader should track this issue concerning making this less of a pain.Plea
V
18

In this snippet:

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

You set (or override) the providers that will be used in your test.

That being said, you can create a different class, a mock if you will, and, using the { provide: originalClass, useClass: fakeClass } notation, provide it instead of the AngularFire actual class.

Something like this:

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
]);

And the AngularFires in your tests will be AngularFireMocks.

Virago answered 26/6, 2016 at 22:52 Comment(0)
M
1

hope it is not off the topic, but the easiest solution I have found how to mock the FirebaseDatabase.

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

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

instead of data:'data' you can mock whatever data you need. The functions can be modified as you wish.

Massage answered 24/3, 2019 at 18:16 Comment(0)
A
0

Similar to @jan, I made a mock using some utility functions:

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

and then you can use them in your spec like this:

 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();
  });
Acting answered 4/11, 2020 at 0:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.