Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

firebase-nightlight

cartant53GPL-3.03.1.2TypeScript support: included

An in-memory, JavaScript mock for the Firebase Web API

firebase, mock, stub, test

readme

firebase-nightlight

GitHub License NPM version Build status dependency status devDependency Status peerDependency Status Greenkeeper badge

What is it?

firebase-nightlight is an in-memory, JavaScript mock for the Firebase Web API.

Why might you need it?

Unit testing services or components that use the Firebase Web API can be tedious:

  • stubbing multiple API methods for each test involves a writing a lot of code, and
  • the alternative of running tests against an actual Firebase project is slow.

You might find using an in-memory mock that can be created and destroyed on a per-test or per-suite basis to be less frustrating.

How does it work?

Each Mock instance implements mocked versions of the properties and methods that are in the firebase namespace. The options passed when creating a Mock instance allow for the specification of the initial database content and authentication identities.

What is mocked?

  • Most of the database API is mocked:
    • References can be used to read, write and query data.
    • Events are mocked and will be emitted between references.
    • Security rules are not mocked.
    • Priorities are not mocked.
    • onDisconnect is not mocked.
    • The sometimes-synchronous nature of child_added events is not mimicked; mocked events are always asynchronous.
  • Some of the auth API is mocked:
    • createUserWithEmailAndPassword,
    • onAuthStateChanged,
    • signInAnonymously,
    • signInWithCredential,
    • signInWithCustomToken,
    • signInWithEmailAndPassword, and
    • signOut are mocked.
    • Other methods are not mocked.
  • The firestore, messaging and storage APIs are not mocked.

Example

import * as firebase from "firebase/app";
import { expect } from "chai";
import { Mock } from "firebase-nightlight";

describe("something", () => {

    let mockDatabase: any;
    let mockApp: firebase.app.App;

    beforeEach(() => {

        mockDatabase = {
            content: {
                lorem: "ipsum"
            }
        };
        const mock = new Mock({
            database: mockDatabase,
            identities: [{
                email: "alice@firebase.com",
                password: "wonderland"
            }]
        });
        mockApp = mock.initializeApp({});
    });

    it("should do something with the mock", () => {

        return mockApp
            .auth()
            .signInWithEmailAndPassword("alice@firebase.com", "wonderland")
            .then((user) => {

                expect(user).to.exist;
                expect(user).to.have.property("email", "alice@firebase.com");
                expect(user).to.have.property("uid");

                return mockApp
                    .database()
                    .ref()
                    .once("value");
            })
            .then((snapshot) => {

                expect(snapshot.val()).to.deep.equal({ lorem: "ipsum" });

                return mockApp
                    .database()
                    .ref()
                    .update({ lorem: "something else" });
            })
            .then(() => {

                expect(mockDatabase.content).to.deep.equal({ lorem: "something else" });

                return mockApp
                    .auth()
                    .signOut();
            });
    });
});

Install

Install the package using NPM:

npm install firebase-nightlight --save-dev

And import the Mock class for use with TypeScript or ES2015:

import { Mock } from "firebase-nightlight";
const mock = new Mock();
console.log(mock);

Or require the module for use with Node or a CommonJS bundler:

const firebaseNightlight = require("firebase-nightlight");
const mock = new firebaseNightlight.Mock();
console.log(mock);

Or include the UMD bundle for use as a script:

<script src="https://unpkg.com/firebase-nightlight"></script>
<script>
var mock = new firebaseNightlight.Mock();
console.log(mock);
</script>

API

Instances of the Mock class implement the properties and methods that are in the Firebase Web API's firebase namespace.

The Mock constructor accepts an options object with the following optional properties:

Property Description
database An object containing the initial database content.
identities An array of identities to use use when authenticating users.
apps An object containing database and identities configurations by app name.

If identities are specified, they can have the following optional properties:

Property Description
credential The firebase.auth.AuthCredential to match if signInWithCredential is called.
email The user's email.
password The password to match if signInWithEmailAndPassword is called.
token The token to match if signInWithCustomToken is called.
uid The user's UID. If not specified, a random UID is generated.

Additions to the Firebase Web API

The mock's implementation of firebase.database.Reference includes a stats_ function that will return the current listener counts for each event type. For example:

mockRef.on("child_added", () => {});
mockRef.on("child_removed", () => {});

const stats = mockRef.stats_();
expect(stats.listeners).to.deep.equal({
    child_added: 1,
    child_changed: 0,
    child_moved: 0,
    child_removed: 1,
    total: 2,
    value: 0
});

Forcing database errors

It's possible to force database errors by delcaring errors in the database content. For example, with this content:

const mockDatabase = {
    content: {
        a: {
            b: {
                ".error": {
                    code: "database/boom",
                    message: "Boom!"
                },
                c: {
                    value: 3
                }
            }
        }
    }
};
const mock = new Mock({
    database: mockDatabase
});

All reads and writes on the a/b path will fail with the specified error. Any reads or writes on deeper paths - a/b/c, for example - will also fail with the specified error.

changelog

3.1.2 (2019-10-05)

Bug Fixes

  • Copy firebase-interfaces.js to dist. (2c5c72b)

Changes

  • Update dependencies and extend the peer ranges.

3.1.1 (2019-08-27)

Bug Fixes

  • Added firebase-interfaces.js for build environments that don't like 'naked' .d.ts files. (14cd9c6)

Changes

  • Update dependencies and extend the peer ranges.

3.1.0 (2018-05-19)

Features

  • Add basic support for Firestore mocking.

3.0.1 (2018-02-16)

Bug Fixes

  • Corrected the handling of the optional name parameter in initializeApp. (06bb983)

3.0.0 (2017-11-23)

Changes

  • Removed preprocessing and removed the mocks internal dependency on the firebase and firebase-admin typings. Hopefully, any minor changes made to the Firebase typings will no longer break firebase-nightlight.
  • There should be no breaking changes, but the internal refactor was significant.

2.2.6 (2017-10-20)

Build

  • Update to latest firebase. (5aa9060)

2.2.5 (2017-10-11)

Build

  • Update to latest firebase. (6b90f70)

2.2.4 (2017-10-04)

Build

  • Restrict firebase dependency semvers due to breaking changes in the typings. (4a76d31)

2.2.3 (2017-09-08)

Build

  • Update to latest firebase. (ab3d959)

2.2.2 (2017-08-18)

Build

  • Update to latest firebase; fix TypeScript interfaces. (f6dfe29)

2.2.1 (2017-07-29)

Build

  • Update to latest firebase; fix TypeScript issues. (9bb2514)

2.2.0 (2017-06-02)

Features

  • Add support for use with firebase-admin (1a97ce6)

2.1.0 (2017-05-27)

Features

  • Add support for declaring errors in the database content (3c674ac) and (7550f49)

2.0.4 (2017-05-27)

Bug Fixes

  • Skip callback when pushing undefined (9fcf75d)

2.0.3 (2017-05-27)

Bug Fixes

  • Support callback for push (4875717)

2.0.2 (2017-05-18)

Features

2.0.1 (2017-05-18)

Features

  • Remove token methods (ba17d23)
  • Add messaging and storage accessors (d6e58d0)

Build

2.0.0 (2017-05-18)

Breaking Changes

1.1.1 (2017-05-02)

Doc

1.1.0 (2017-05-01)

Features

  • ref: Add stats_ function for counting listeners (80dfc59)

1.0.9 (2017-04-30)

Bug Fixes

  • query: Support missing children (5484ee0)

1.0.8 (2017-04-29)

Bug Fixes

  • ref: Resolve ThenableReference returned by push (934d876)
  • auth: Emit the current auth state from onAuthStateChanged (f1e761a)
  • ref: Hide invalid methods (da2d6c9)
  • ref: Mock .info (5197ccd)
  • ref: Skip shared event listener when possible (eba0e07)
  • query: Prevent non-matching events (6d35552)

1.0.7 (2017-04-29)

Bug Fixes

  • query: Use optional key only when equal (f718f9b)

1.0.6 (2017-04-29)

Bug Fixes

  • query: Support optional key (150573f)

1.0.5 (2017-04-29)

Bug Fixes

  • query: Fix null comparisons (0d6107c)

1.0.4 (2017-04-27)

Bug Fixes

  • child_removed: Use previous snapshot (d670987)