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:
Three steps to begin testing.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With