Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit tests for firebase add using angular 2

Does anyone know how to do a basic unit test using angular 2 to test a basic firebase add item.

I'm using typescript instead of basic JavaScript for my code

This is what I'm testing:

 export class AppComponent {
     ref: Firebase;
     refUsers: Firebase;
     refProfiles: Firebase;

     constructor(){
         this.ref = new Firebase("https://markng2.firebaseio.com");
         this.refUsers = new Firebase("https://markng2.firebaseio.com/users");
         this.refProfiles = new Firebase("https://markng2.firebaseio.com/profiles");    
     }

     public addUser(newUser: Object): void{     
         this.refUsers.push(newUser, ()=>{

         });
     }
 }

This is my current test:

 import {it, iit, describe, expect, inject, injectAsync, beforeEachProviders, fakeAsync, tick } from 'angular2/testing';
 import { AppComponent } from '../app/app';

 describe('AppComponent', () => {

     it('saves an item to Firebase', () => {
         let refUsers = new Firebase('');

         let service = new AppComponent();

         spyOn(service.refUsers, 'push');
         service.addUser({ item: true });

         expect(service.refUsers.push).toHaveBeenCalled();
     })

 });

This is the error I'm getting when I run that test:

enter image description here

like image 420
AngularM Avatar asked Dec 02 '15 13:12

AngularM


1 Answers

Three steps to begin testing.

  1. Setup your testing environment. The Angular 2 docs have a great guide on doing so.
  2. Write your code.
  3. Write the test.

Let's say you create a class called DataService:

/// <reference path="typings/firebase/firebase.d.ts" />

export class DataService {
    ref: Firebase;
    constructor(theRef: Firebase) {
        this.ref = theRef;
    }
    add(object: any) {
        this.ref.push(object);
    }
}

To test it, you can import DataService and use Jasmine methods to test that the add method.

import {DataService} from './data-service';

describe('DataService', () => {

    it('saves an item to Firebase', () => {
        let ref = new Firebase('');
        let service = new DataService(ref);
        // create a spy to use if push is called
        spyOn(service.ref, 'push');
        service.add({ item: true });
        // expect that push was called
        expect(service.ref.push).toHaveBeenCalled();
    })

});

The key to testing Firebase methods is just to spy on them. You don't need to test that Firebase works, just that your code calls Firebase properly.

The problem here is that you're using the full Firebase SDK in your unit tests. Ideally you'd want to use a mocked library, so you can create a mock for whatever functionality you need from the Firebase SDK.

like image 97
David East Avatar answered Oct 16 '22 18:10

David East