Giter Site home page Giter Site logo

soumak77 / firebase-mock Goto Github PK

View Code? Open in Web Editor NEW
347.0 8.0 97.0 2.99 MB

Firebase mock library for writing unit tests

Home Page: https://soumak77.github.io/firebase-mock

JavaScript 100.00%
firebase firebase-admin firebase-database firebase-auth firebase-firestore firebase-functions firebase-storage testing unit-testing mock

firebase-mock's Introduction

Firebase Mock Build Status

Firebase Mock extends mockfirebase to provide support for the following Firebase Javascript SDKS:

Setup

npm install firebase-mock --save-dev

Follow the steps in the Setup Tutorial to create a mock SDK to be used in your tests. Then follow one of the tutorials below based on your testing framework:

API

Firebase Mock supports the client-side JavaScript API and server-side Admin API plus a small set of utility methods documented fully in the API Reference. Rather than make a server call that is actually asynchronous, Firebase Mock allows you to either trigger callbacks synchronously or asynchronously with a specified delay (ref.flush).

Tutorials

Client (firebase)

Functions (firebase-functions)

Alternatives

firebase-mock's People

Contributors

a-xin avatar adrianosmond avatar andrei-e-random avatar andrewkvalheim avatar bendrucker avatar boyko avatar brettatoms avatar chetbox avatar curtishumphrey avatar fredyc avatar gajuro avatar huafu avatar ilearnio avatar jamestalmage avatar joshlory avatar jqrgen avatar justintulloss avatar katowulf avatar kennethlynne avatar lewchuk-inkling avatar ltomes avatar mwq27 avatar rbokel avatar rhodgkins avatar rlivsey avatar simonajones avatar soumak77 avatar squirly avatar yearofthedan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-mock's Issues

fakeEvent implicitly called value subscriber is missing its value

When I add a value subscriber to a new child when it is added, firebase-mock immediately calls the subscriber (as it should), but without the value set in the ref passed to the subscriber.
Real firebase calls the subscriber with the value set.

Here is a jasmine test that shows this behavior:

describe("adding a child", () => {
  let ref;
  beforeEach(() => {
    ref = firebase.database().ref('/some-ref').push();
  });

  describe("when subscribing to newly added values", ()=> {
    let valueCallbackSpy;

    beforeEach(() => {
      valueCallbackSpy = jasmine.createSpy('valueCallbackSpy');

      ref.on('child_added', function (snapshot) {
        snapshot.ref.on('value', valueCallbackSpy);
      });
    });

    it("calls the value subscriber", ()=> {
      ref.fakeEvent('child_added', 'some-key', 'some-value', '');
      ref.flush();

      expect(valueCallbackSpy).toHaveBeenCalled();
    });

    it("passes a key and value to the subscriber", ()=> {
      ref.fakeEvent('child_added', 'some-key', 'some-value', '');
      ref.flush();
      let snapshot = valueCallbackSpy.calls.argsFor(0)[0];
      expect(snapshot.key).toEqual('some-key');
      expect(snapshot.val()).toEqual('some-value'); // ** this line fails because val() is null **
    });
  });
});

Alternatively if triggering the fake child_added event didn't call the value subscriber at all, I think that would be okay. One could call that manually as a separate fake event. It's kind of strange that the 'value' event gets queued up and called within the same flush action.

Running MockFirebase under Web Worker

In the last several days I did extensive research to solve an issue running MockFirebase under a Web Worker. After reading Issue 131 of Lodash, I noticed that included under firebase-mock/node_modules is Lodash 2.x.

My quick fix is to rename firebase-mock/node-modules so it is excluded from normal Node search path, forcing a newer version of Lodash 3.x included in my build.

Auth error mock

Hi,

Is it possible to simulate an auth error even?
Didn't find anything in the docu about that.

Thx

Mock FirebaseUser

Thanks for this great library! One piece that is missing is a set of mocks around the FirebaseUser class, (which is passed in to the onAuthStateChanged() callback). I'm trying to test that use of helper methods (e.g., updateProfile()) are working correctly, but since currently the returned firebase user is just a plain object, this functionality isn't available.

limitToFirst and limitToLast are not supported

I run into an error when testing code that uses limitToFirst.

TypeError: ref.limitToFirst is not a function

My code looks like this:

ref.orderByKey()
.startAt('abc')
.limitToFirst(10)
.once('value')
.then( /* ... */ );

mock-firebase with Jest testing

I have this react project setup with the infamous create-react-app project, and testing for that defaults to Jest, which gets the job done. I'm trying to test out a class I created to initialize a store for a certain firebase ref, like so: (I'm using mobx to handle observable stores)

BadgeStore.js

import { observable, action } from 'mobx'
import fb from '../firebaseConfig'

var db = fb.database()

class BdgeStore {
  constructor () {
    this.badges = observable({arr: new Array(0)})
  }

  @action.bound
  activate () {
    var badgesRef = db.ref('badges')
    badgesRef.on('value', (snapshot) => {
      this.badges.arr = new Array(0)
      snapshot.forEach(b => {
        // Make sure that the badge values exist:
        const badge = {
          name: b.val().name ? b.val().name : '',
          id: b.key
        }
        this.badges.arr.push(badge)
      })
    })
  }
}
var BadgeStore = new BdgeStore()
export default BadgeStore

Note that fb is an instance of firebase initialized with the web config API keys, etc. This works great, the application runs fine in firebase. For my test, I have the following:
BadgeStore.test.js

var proxyquire = require('proxyquire')
var firebasemock = require('firebase-mock')

var mockdatabase = new firebasemock.MockFirebase()
var mockauth = new firebasemock.MockFirebase()
var mocksdk = firebasemock.MockFirebaseSdk(function (path) {
  return mockdatabase.child(path)
}, function () {
  return mockauth
})

let BadgeStore = proxyquire('./BadgeStore', {
  fb: mocksdk
})
mockdatabase.flush()

describe('Badge Store', () => {
  it('constructs with an empty array', () => {
    expect(BadgeStore.badges.arr.length).toBe(0)
  })
  /* ... etc... */
}

Now, my problem is the following. When I run npm test, I get the following result in the console:

 FAIL  src\state\stores\BadgeStore.test.js
  โ— Test suite failed to run

    TypeError: Cannot read property 'bind' of undefined

      at Proxyquire.Object.<anonymous>.Proxyquire.load(node_modules/proxyquire/lib/proxyquire.js:136:79)
      at Object.<anonymous> (src/state/stores/BadgeStore.test.js:16:18)

I'm not 100% sure what this means. Looking into the file, it seems as if it's not finding the firebase reference to replace? Help on this issue would be greatly appreciated. Thanks!

Use of orderByKey().startAt('desiredKey') always returns empty snapshot

Queries support limitToFirst but not startAt. Example:

var firebasemock  = require('firebase-mock');

var mockdatabase  = new firebasemock.MockFirebase();
var mockauth      = new firebasemock.MockFirebase();
var mocksdk       = firebasemock.MockFirebaseSdk(function(path) {
  return mockdatabase.child(path);
}, function() {
  return mockauth;
});

var ref = mocksdk.database().ref('data');
ref.child('key1').set('value1');
ref.child('key2').set('value2');
ref.child('key3').set('value3');
mockdatabase.flush();

function runQuery(query) {
	query.once('value').then(snapshot => {
		console.log(snapshot.numChildren());
		snapshot.forEach((childSnapshot) => {
			console.log(childSnapshot.key);
		});
	});
	mockdatabase.flush();
}

runQuery(ref.orderByKey().limitToFirst(2));
runQuery(ref.orderByKey().startAt('key2').limitToFirst(2));

Output:

2
key1
key2
0

Expected Output:

2
key1
key2
2
key2
key3

Database arrays

I'm storing arrays in the Firebase database. For example:

  const schemas = firebase.database().ref(`/schemas/${groupKey}`);

  schemas.set({
    order: [ 'firstName', 'lastName', 'dateAdded' ],
    required: [ 'firstName', 'lastName', 'dateAdded' ],
    properties: {
      dateAdded: {
        'description': 'Date Added',
        'maximum': 0,
        'type': 'integer'
      },
      firstName: {
        'description': 'First Name',
        'type': 'string'
      },
      lastName: {
        'description': 'Last Name',
        'type': 'string'
      },
    },
    title: 'Generic Schema',
    type: 'object',
  });

Basically, a JSON schema.

This seems to work just fine when not mocking. When retrieving data, I get an array for 'required' and 'order' properties above. Now, when using firebase-mock, the above data gets converted to:

{
  "order": {
    "0": "firstName",
    "1": "lastName",
    "2": "dateAdded"
  },
  "properties": {
    "dateAdded": {
      "description": "Date Added",
      "maximum": 0,
      "type": "integer"
    },
    "firstName": {
      "description": "First Name",
      "type": "string"
    },
    "lastName": {
      "description": "Last Name",
      "type": "string"
    }
  },
  "required": {
    "0": "firstName",
    "1": "lastName",
    "2": "dateAdded"
  },
  "title": "Generic Schema",
  "type": "object"
}

This Firebase article looks relevant. Didn't know that arrays are handled in an odd way in Firebase.

Research supporting firestore rules

It would be extremely helpful to be able to set firestore rules during unit testing. The MockFirebase class can be updated to take in a JSON object specifying the rules for specific documents. Those rules can then get parsed and applied to any CRUD operations on the documents. This would only be useful for client-side testing as the firestore security rules do not apply for firebase-admin or firebase-functions.

Ideally the library would support using the exact rules file that is uploaded to firebase. I don't know how difficult it would be to parse that file into executable javascript code. Function definitions are already javascript, so there would just need to be a way to parse the file and extract the match and allow expressions. The end result would be a javascript object which has the necessary values to perform regex matching on the document paths and provide various functions to execute for CRUD operations on those documents. Assuming that was all possible, it would be fairly straight forward to provide support for built-in functions (e.g. get and $) and pass mocked values to functions (e.g. request and resource).

What is the right way to test firestore code in jest?

I am getting this error when trying to fetch a document.
Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
It seems to get stuck when calling docRef.get()
Source code:

const docRef = firestore.collection('userOwned').doc(uid);
const doc = await docRef.get();

Here is my source config:

import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import 'firebase/firestore';


const config = {
    apiKey: '',
    authDomain: '',
    databaseURL: '',
    projectId: '',
    storageBucket: '',
    messagingSenderId: ''
};

firebase.initializeApp(config);

const auth = firebase.auth();
const database = firebase.database();
const firestore = firebase.firestore();

export {
    auth,
    database,
    firestore
};

I mock the config file:

jest.mock('../firebase', () => {
    const firebasemock = require('firebase-mock');

    const mockdatabase = new firebasemock.MockFirebase();
    const mockauth = new firebasemock.MockFirebase();
    const mocksdk = new firebasemock.MockFirebaseSdk(
        path => {
            return path ? mockdatabase.child(path) : mockdatabase;
        },
        () => {
            return mockauth;
        }
    );
    const mockfirestore = new firebasemock.MockFirestore();

    const firebase = mocksdk.initializeApp(); // can take a path arg to database url
    // optional - expose the mock
    global.firebase = firebase;

    // return the mock to match your export api
    return {
        auth: mockauth,
        database: mockdatabase,
        firestore: mockfirestore
    };
});

and try to add some mock data:

import { firestore } from '../../firebase';
firestore
    .collection('userOwned')
    .doc(mockuid)
    .set(mockdata);

The module md5 is not present when installing firebase-mock

The symptom

When attempting to require firebase-mock auth or bundling firebase-mock with a webpack

./node_modules/firebase-mock/src/login.js
Module not found: `/Users/apaz/code/github.com/alexjpaz/liftit/packages/web/node_modules/md5/md5.js` does not match the corresponding path on disk `MD5`.

This seems to affect the build when using yarn or npm. I can confirm that the module md5 is not present (however md5.js is).

Workaround

Manually running npm --save-dev md5 seems to resolve the issue.

yarn.lock snippet

md5.js@^1.3.4:
  version "1.3.4"
  resolved "https://registry.yarnpkg.com/md5.js/-/md5.js-1.3.4.tgz#e9bdbde94a20a5ac18b04340fc5764d5b09d901d"
  dependencies:
    hash-base "^3.0.0"
    inherits "^2.0.1"

md5@^2.2.1:
  version "2.2.1"
  resolved "https://registry.yarnpkg.com/md5/-/md5-2.2.1.tgz#53ab38d5fe3c8891ba465329ea23fac0540126f9"
  dependencies:
    charenc "~0.0.1"
    crypt "~0.0.1"
    is-buffer "~1.1.1"

Tutorial outdated + initializeApp() mock needed

Hello

I'm trying to implement the tutorial for overriding require('firebase') on a node server using firebase API v3. I get the following message when ref.on('value', function (snapshot) { is executed:

[DEFAULT]: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
    at M (/home/jorgen/flareserver/node_modules/firebase/app-node.js:28:397)
    at a (/home/jorgen/flareserver/node_modules/firebase/app-node.js:26:68)
    at Function.c [as database] (/home/jorgen/flareserver/node_modules/firebase/app-node.js:27:492)
    at Object.<anonymous> (/home/jorgen/flareserver/mySrc.js:3:23)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Object.require.extensions.(anonymous function) (/home/jorgen/flareserver/node_modules/proxyquire/lib/proxyquire.js:276:43)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)

Looking at the firebase-mock library there seems to be no override/mock for the initializeApp() function used to initialize the firebase lib on node.js servers.

My current implementation:
// ./mySrc.js:
var firebaseApp = require('firebase');

var ref = firebaseApp.database().ref();
ref.on('value', function (snapshot) {
	console.log(snapshot.val());
});
// ./test.js
var proxyquire   = require('proxyquire');
var MockFirebase = require('firebase-mock').MockFirebase;
var mock;

var mySrc = proxyquire('./mySrc', {
	firebase: function (url) {
		mock = new MockFirebase(url);
		console.log(mock);
		return mock;
	}
});

mock.flush();
// data is logged

Thanks
JQ

When set is called with object with numeric keys, get returns an array

Calling set with an object with numeric keys, causes .once('value') to return an array:

  const obj = { 1: "foo", 2: "bar" }
  await database.ref("expenses").set(obj);
  const snapshot = await database.ref("expenses").once("value");
  console.log("snapshot.val()", snapshot.val());

Output:

snapshot.val() [ undefined, 'foo', 'bar' ]

If the object has at least one non-numeric key, it is correctly returned.

Mocking ref.update

Hello

I'm trying to mock a ref.update function but it does not seem to work.
is ref.update() a part of the library?
Where can I see what methods are implemented in the library or not? I would love to extend it.

Code (Angular controller):

this.userRef = null;
    this.user = {
      ref: function (uid) {
        if (!that.userRef) that.userRef = firebase.database().ref().child('users/' + uid);
        return that.userRef;
      },
      update: function () {
        return that.user.ref("asdasdsdasd").update({
          phone: false,
          verification_code: false,
          country: false
        }, function (error){
          console.log("lol");
          if(error){
            throw error;
          }
        });
      }
    };

Jasmine test:

    MockFirebase.override();

    var userRef = ctrl.user.update("FAKEID");
    userRef.flush(); //  throws: TypeError: Cannot read property 'flush' of undefined

Thanks for any help.

FirebaseAuth has no defer

I'm trying to mock FirebaseAuth, but I got error cause has no _defer function in FirebaseAuth.

 TypeError: self._defer is not a function
      
      at defer (node_modules/firebase-mock/src/auth.js:39:10)
      at FirebaseAuth.Object.<anonymous>.FirebaseAuth.onAuthStateChanged (node_modules/firebase-mock/src/auth.js:31:3)
      at Function.init$ (app/services/Auth/auth.service.js:22:17)
      at tryCatch (node_modules/regenerator-runtime/runtime.js:65:40)
      at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:303:22)
      at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:117:21)
      at tryCatch (node_modules/regenerator-runtime/runtime.js:65:40)
      at invoke (node_modules/regenerator-runtime/runtime.js:155:20)
      at node_modules/regenerator-runtime/runtime.js:165:13
      at tryCallOne (node_modules/promise/lib/core.js:37:12)

How can I implement this?

createUserWithEmailAndPassword not working with v3?

Hello

The pattern in the authentication tutorial: is using a deprecated firebase v2 callFirebase('https://example.firebaseio.com'); instead of v3 firebase.auth() from v3(;. Currently using firebase v3 crashes my test.

โœ– 1 test failed

FAILED TESTS:
  AlarmButtonEvents
    โœ– Should init authdata
      Chrome 56.0.2924 (Linux 0.0.0)
    TypeError: Cannot read property 'createUserWithEmailAndPassword' of undefined
        at Object.create (http://localhost:1337www/services/firebase.service.js:14:20)
        at Object.<anonymous> (http://localhost:1337www/app/alarmbutton/alarmbutton.events.factory.spec.js:42:25)

How users are created in the client:

.service('firebaseService', function() {
     var that = this;

     this.users = {
     	ref: function () {
     		firebase.auth();
	},
     create: function (credentials) {
	that.users.ref().createUserWithEmailAndPassword(credentials).catch(function(error) {
		// Handle Errors here.
		var errorCode = error.code;
		 var errorMessage = error.message;
		// ...
		});
	}
     };
});

unit test:

it('Should init authdata', function(){
	MockFirebase.override();
	firebaseService.users.ref();
	firebaseService.users.create({
		email: '[email protected]',
		password: 'examplePass'
	});
	firebaseService.flush();
	console.assert(firebaseService.getEmailUser('[email protected]'), 'ben was created');
});

Missing where on firestore collections

I get an error about prs.where is not a function when I try the following code with firebase mock:

const store = new MockFirestore();
const prs = store.collection('prs');
prs.where('repository', '==', repository.id)
   .where('state', '==', 'open')
   .get()

This is valid firestore code (it works without the mock).

For now I've patched it with

prs.where = () => prs;

Updating nested value via a transaction leads to inconsistent data

Adding the following test to test/unit/firebase.js (MockFirebase #transaction):

it('should allow updating nested values in transactions', function () {
  ref.set({
    item: {
      meta: {
        time: 1234,
      },
    },
  });
  ref.flush();

  ref.child('item').transaction(function(value) {
    if (value) {
      value.meta.time = 9999;
    }

    return value;  
  });
  ref.flush();
  
  expect(ref.getData().item).to.equal(ref.child('item').getData());
});

Fails with:

AssertionError: expected { meta: { time: 1234 } } to equal { meta: { time: 9999 } }
+ expected - actual

  {
    "meta": {
-    "time": 1234
+    "time": 9999
    }
  }

I would have expected both paths to return the updated data and therefore the test to pass.

How to fire firebase.once() in express middleware

Hey

I'm using mocha/chai for unit testing middleware on a node/express server.

The firebase.once call is inside of a promise function which is used as middleware.
Using the following function from chai does not seem to work because firebase.once is never fired

return expect(middleware.getUsers(req)).to.be.fulfilled.then(..)

The middleware and unit tests are defined as follows using the pattern found here

middleware.test.js
const httpMocks = require('node-mocks-http');
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const proxyquire = require('proxyquire');
const firebasemock = require('firebase-mock');
const expect = chai.expect;

chai.use(chaiAsPromised);

const mockdatabase = new firebasemock.MockFirebase();
const mockauth = new firebasemock.MockFirebase();
const mocksdk = firebasemock.MockFirebaseSdk(function() {
	return mockdatabase;
}, function() {
	return mockauth;
});

const middleware = proxyquire('../app/middleware.js', {
	'firebase-admin': mocksdk
});
var req, res;

beforeEach(function(done){
	req = httpMocks.createRequest();
	res = httpMocks.createResponse();
	done();
});

describe('middleware', function() {
	it('gets users', function(){
		mockdatabase.ref.child('users').push({
			users: 'test'
		});
		mockdatabase.ref.flush(); // Where should this be placed in this case?

		return expect(middleware.getUsers(req)).to.be.fulfilled.then(function(){
                       // This is never reached.
			console.log('req.usersSnap');
			console.log(req.usersSnap);
			mockdatabase.flush();
		});
	});
});
middleware.js:
const calculate = require('./services/calculate.js');
const Q = require('q');
const firebase = require('firebase-admin');
const ref = firebase.database().ref();

const middleware = {
	getUsers: function(req) {
		const deferred = Q.defer();
		ref.child('users').once('value') // This never fires.
		.then((usersSnap)=>{
			req.usersSnap = usersSnap;
			deferred.resolve();
		})
		.catch((error)=>{
			deferred.reject(error);
		});

		return deferred.promise;
	},
route.js
const router = require('express').Router();
const middleware = require('../middleware.js');

router.get('/', function (req, res, next) {
	middleware.getUsers(req)
		.then(function () {
			next();
		})
		.catch(res.json)
		.done();
});

module.exports = router;

Thanks for any help.

firebase.auth.GithubAuthProvider.credential Error

My test is about generate a new Github credential, but when I run, I got the error:
TypeError: firebase.auth.GithubAuthProvider.credential is not a function
I believe that error is because the sdk.js return a function:
MockFirebaseAuth.GithubAuthProvider = function ...
If I change that file to use a JSON Object I get the expected result...

I use that because I need call after the signInWithCredential, but I can test that signin now.
It's needed change the code in any PR or I can make something for evict that way?

Question on using Database as the origin of data.

Hi, I would like to ask why are updates recorded on Reference level and not on Database level?

I think it might be useful if you could pass a database as a function argument and then flush updates to multiple refs simultaneously.

Do you agree? Is this an approach that firebase-mock could adopt in the future?

when set is called with an empty-array child, the wrong results are returned in some cases

When the 'set' value includes an empty array, fetching a child in some cases will discard alphabetically later siblings of the empty array's parent and include the the parent even though it has no valid firebase children.

MockFirebase should mimic Firebase's behavior during the set call and ignore values that have no [string, null, number, boolean, ServerValue.Timestamp, etc.] as children. Empty arrays and empty objects are non-entities as far as firebase is concerned.

describe("when 'set' value includes an empty array", () => {
  let ref;
  beforeEach(() => {
    ref = firebase.database().ref('/someRef');
    ref.set(
      {
        someParent: {
          zag: 'some-value',
          aardvark: 'some-value',
          someKey: { someEmptyArray: [] },
          zippityZap: 'some-value'
        }
      });
  });

  it("unfortunately discards alphabetically later siblings of the problematic key", () => {
    let someSpy = sandbox.spy();
    ref.child('someParent').once('value', (snapshot) => {
      someSpy(snapshot.val())
    });
    ref.flush();
    expect(someSpy.lastCall.args[0].aardvark).to.eq('some-value');
    expect(someSpy.lastCall.args[0].zag).to.eq(undefined);
    expect(someSpy.lastCall.args[0].zippityZap).to.eq(undefined);
  });

  it("unfortunately includes the empty parent", () => {
    let someSpy = sandbox.spy();
    ref.child('someParent').once('value', (snapshot) => {
      someSpy(snapshot.val())
    });
    ref.flush();
    expect(someSpy.lastCall.args[0].someKey).to.deep.eq({ someEmptyArray: [] });
  });

  it("should exclude the empty parent of the empty array from the result", () => {
    let someSpy = sandbox.spy();
    ref.child('someParent').once('value', (snapshot) => {
      someSpy(snapshot.val())
    });
    ref.flush();
    expect(someSpy.lastCall.args[0].someKey).to.eq(undefined);
  });

  it("should include all populated values", () => {
    let someSpy = sandbox.spy();
    ref.child('someParent').once('value', (snapshot) => {
      someSpy(snapshot.val())
    });
    ref.flush();
    expect(someSpy.lastCall.args[0].zag).to.eq('some-value');
    expect(someSpy.lastCall.args[0].zippityZap).to.eq('some-value');
    expect(someSpy.lastCall.args[0].aardvark).to.eq('some-value');
  });
});

Add orderBy behavior

firebase-admin-mock was deprecated in favor of this library, but this one doesn't support orderBy while firebase-admin-mock did. That's a really critical feature that prevents us from using this library.

https://github.com/sebasgarcep/firebase-admin-mock/blob/42bd3d862e28004ae97a7eed35b622843ccde05a/lib/database-accesors.js#L81

It's unfortunate that project was immediately archived without having feature parity over here yet. Hopefully firebase-mock can get the same features!

@sebasgarcep

`MockFirebase.prototype.root` should be a property instead of a function

According to the docs, root of firebase.database.Reference should be a property pointing to another Reference:

root
non-null firebase.database.Reference
The root Reference of the Database.
https://firebase.google.com/docs/reference/js/firebase.database.Reference#root

firebase-mock implements root as a method, which makes code that runs fine with the firebase sdk break while running with firebase-mock:

// Works with firebase sdk but fails with firebase-mock
const userRef = ref.root.child('users');

Code:

MockFirebase.prototype.root = function () {

Failing a ref.once call

Hello

It would be nice to be able to cause ref.once call to fail. I'm currently calling

this.somefunction = function(){
    ref.child('/phone_numbers/' + phone).once(...) 
}

in an angular controller and in my test code(jasmine) the following code does not cause the ref.once call to fail:

ctrl.firebaseRef.failNext('update', error);
ctrl.somefunction();
ctrl.firebaseRef.flush();

Thus I want ref.once() to fail and return an error in the callback so that I can throw an error and catch it in my test.

I would implement it into the library myself but I'm a beginner in unit testing & mocking and I cant seem to figure out how this mock library works so that I can extend it.

A new feature or a guidance on how I could implement it myself would be awesome.

JQ

Add equalTo behavior

This was supported by firebase-admin-mock which was deprecated in favor of this library.

https://github.com/sebasgarcep/firebase-admin-mock/blob/42bd3d862e28004ae97a7eed35b622843ccde05a/lib/database-accesors.js#L48

It should be easy to implement if you already have startAt/endAt since it's the same as setting the range endpoints to the same value. No reason to use spies there.

This is all the real firebase SDK does as well:
https://github.com/firebase/firebase-js-sdk/blob/73a586c92afe3f39a844b2be86086fddb6877bb7/packages/database/src/api/Query.ts#L565

@sebasgarcep

Unexpected error when installing through yarn

First off, thanks for the library. It is great to have this all wrapped up in one place.

Recently I started getting an error when installing through yarn:

An unexpected error occurred: "Couldn't find package \"lodash@^3.10.1\" required by \"firebase-mock@^2.1.0\" on the \"npm\" registry.".

Its weird though since lodash does have a 3.10.1 (confirmed through npm view lodash). It shouldn't matter, but I have another version of lodash already installed (4.17.5) in that project.

While we talking about lodash I had few questions:

  • Is there a reason that lodash 3.10.1 is still being used?
  • Are you open to looking into module lodash (either through slash requires or babel + plugin)? It could help reduce size quite a bit
  • What are your thoughts on setting up babel? Some things could then be native JS over libraries. Totally open to helping - I saw #50 was about native promises, it would be pretty easy to capture both at once

Add suport for order queries

Hi, great job on the mock working very nice so far ๐Ÿ˜„
Order queries like someRef.orderByChild('index') are not supported. Do you plan to support them?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.