GithubHelp home page GithubHelp logo

philmod / firestore-jest-mock Goto Github PK

View Code? Open in Web Editor NEW

This project forked from sbatson5/firestore-jest-mock

1.0 2.0 0.0 552 KB

Jest Helper library for mocking Cloud Firestore

Home Page: https://www.npmjs.com/package/firestore-jest-mock

JavaScript 100.00%

firestore-jest-mock's Introduction

Mock Firestore

Jest Mock for testing Google Cloud Firestore

A simple way to mock calls to Cloud Firestore, allowing you to assert that you are requesting data correctly.

This is not a pseudo-database -- it is only for testing you are interfacing with firebase/firestore the way you expect.

Table of Contents

What's in the Box

This library provides an easy to use mocked version of firestore.

Installation

With npm:

npm install --save-dev firestore-jest-mock

With yarn:

yarn add --dev firestore-jest-mock

Usage

mockFirebase

The default method to use is mockFirebase, which returns a jest mock, overwriting firebase and firebase-admin. It accepts an object with two pieces:

  • database -- A mock of your collections
  • currentUser -- (optional) overwrites the currently logged in user

Example usage:

const { mockFirebase } = require('firestore-jest-mock');
// Create a fake firestore with a `users` and `posts` collection
mockFirebase({
  database: {
    users: [
      { id: 'abc123', name: 'Homer Simpson' },
      { id: 'abc456', name: 'Lisa Simpson' },
    ],
    posts: [{ id: '123abc', title: 'Really cool title' }],
  },
});

This will populate a fake database with a users and posts collection.

Now you can write queries or requests for data just as you would with firestore:

test('testing stuff', () => {
  const firebase = require('firebase'); // or import firebase from 'firebase';
  const db = firebase.firestore();

  db.collection('users')
    .get()
    .then(userDocs => {
      // write assertions here
    });
});

What would you want to test?

The job of the this library is not to test firestore, but to allow you to test your code without hitting firebase. Take this example:

function maybeGetUsersInState(state) {
  const query = firestore.collection('users');

  if (state) {
    query = query.where('state', '==', state);
  }

  return query.get();
}

We have a conditional query here. If you pass state to this function, we will query against it; otherwise, we just get all of the users. So, you may want to write a test that ensures you are querying correctly:

const { mockFirebase } = require('firestore-jest-mock');

// Import the mock versions of the functions you expect to be called
const { mockCollection, mockWhere } = require('firestore-jest-mock/mocks/firestore');
describe('we can query', () => {
  mockFirebase({
    database: {
      users: [
        { id: 'abc123', name: 'Homer Simpson' },
        { id: 'abc456', name: 'Lisa Simpson' },
      ],
    },
  });

  test('query with state', async () => {
    await maybeGetUsersInState('alabama');

    // Assert that we call the correct firestore methods
    expect(mockCollection).toHaveBeenCalledWith('users');
    expect(mockWhere).toHaveBeenCalledWith('state', '==', 'alabama');
  });

  test('no state', async () => {
    await maybeGetUsersInState();

    // Assert that we call the correct firestore methods
    expect(mockCollection).toHaveBeenCalledWith('users');
    expect(mockWhere).not.toHaveBeenCalled();
  });
});

In this test, we don't necessarily care what gets returned from firestore (it's not our job to test firestore), but instead we try to assert that we built our query correctly.

If I pass a state to this function, does it properly query the users collection?

That's what we want to answer.

Don't forget to reset your mocks

In jest, mocks will not reset between test instances unless you specify them to. This can be an issue if you have two tests that make an asseration against something like mockCollection. If you call it in one test and assert that it was called in another test, you may get a false positive.

Luckily, jest offers a few methods to reset or clear your mocks.

  • clearAllMocks() clears all the calls for all of your mocks. It's good to run this in a beforeEach to reset between each test
jest.clearAllMocks();
mockCollection.mockClear();

I wrote a where clause, but all the records were returned!

The where clause in the mocked firestore will not actually filter the data at all. We are not recreating firestore in this mock, just exposing an API that allows us to write assertions. It is also not the job of the developer (you) to test that firestore filtered the data appropriately. Your application doesn't double-check firestore's response -- it trusts that it's always correct!

Functions you can test

Firestore

Method Use Method in Firestore
mockCollection Assert the correct collection is being queried collection
mockCollectionGroup Assert the correct collectionGroup is being queried collectionGroup
mockDoc Assert the correct record is being fetched by id. Tells the mock you are fetching a single record doc
mockWhere Assert the correct query is written. Tells the mock you are fetching multiple records where
mockBatch Assert batch was called batch
mockBatchDelete Assert correct refs are passed batch delete
mockBatchCommit Assert commit is called. Returns a promise batch commit
mockGet Assert get is called. Returns a promise resolving either to a single doc or querySnapshot get
mockGetAll Assert correct refs are passed. Returns a promise resolving to array of docs. getAll
mockUpdate Assert correct params are passed to update. Returns a promise update
mockAdd Assert correct params are passed to add. Returns a promise resolving to the doc with new id add
mockSet Assert correct params are passed to set. Returns a promise set
mockDelete Assert delete is called on ref. Returns a promise delete
mockOrderBy Assert correct field is passed to orderBy orderBy
mockLimit Assert limit is set properly limit

Auth

Method Use Method in Firebase
mockCreateUserWithEmailAndPassword Assert correct email and password are passed. Returns a promise createUserWithEmailAndPassword
mockDeleteUser Assert correct id is passed to delete method. Returns a promise deleteUser
mockSendVerificationEmail Assert request for verification email was sent. Lives on the currentUser sendVerificationEmail
mockSignInWithEmailAndPassword Assert correct email and password were passed. Returns a promise signInWithEmailAndPassword
mockSendPasswordResetEmail Assert correct email was passed. sendPasswordResetEmail
mockVerifyIdToken Assert correct token is passed. Returns a promise verifyIdToken

Contributing

We welcome all contributions to our projects! Filing bugs, feature requests, code changes, docs changes, or anything else you'd like to contribute are all more than welcome! More information about contributing can be found in the contributing guidelines.

To get set up, simply clone this repository and npm install!

Code of Conduct

Upstatement strives to provide a welcoming, inclusive environment for all users. To hold ourselves accountable to that mission, we have a strictly-enforced code of conduct.

About Upstatement

Upstatement is a digital transformation studio headquartered in Boston, MA that imagines and builds exceptional digital experiences. Make sure to check out our services, work, and open positions!

firestore-jest-mock's People

Contributors

bchiang7 avatar beahuang avatar dependabot[bot] avatar joshpensky avatar

Stargazers

 avatar

Watchers

 avatar  avatar

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.