Unit tests for adding firebase using angular 2

Does anyone know how to do a basic unit test with angular 2 to test the element of adding a basic Firebase base.

I use typescript instead of basic JavaScript for my code

This is what I am 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 get when doing this test:

enter image description here

+5
source share
1 answer

Three steps to start testing.

Suppose you created 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 the DataService and use the Jasmine methods to verify 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 simply to keep track of them. You do not need to verify that Firebase is working, just that your code correctly calls Firebase.

The problem is that you are using the full Firebase SDK in your unit tests. Ideally, you would like to use the mock library so you can create a layout for any functionality you need from the Firebase SDK.

+2
source

Source: https://habr.com/ru/post/1237248/


All Articles