zlZimon
zlZimon

Reputation: 2489

How to mock firestore with mocha

I have a simple wrapper function which returns a specific document from firestore like so:

export const fetchSettings = async (firestore):Promise<MyDocment>=>{
    try {
        const response = await firestore
            .collection('someCollection')
            .doc('someDoc')
            .get();
        const data = response.data()!;
        return {
          dataOne: data.someDataOne,
          dataTwo: data.someDataTwo
        };
    } catch (error) {
        console.log(error);
        return error;
    }
};

This function is used in other function I want to test and therefore I would like to mock firestore to return a specific document the exact way this implementation would do.

How can I do this with mocha? With jest I could have something like jest.fn(()=>Promise.resolve({dataOne:'somedata', dataTwo:'someotherdata'}));

What is the mocha way to do this?

Upvotes: 0

Views: 885

Answers (2)

Lin Du
Lin Du

Reputation: 102327

Mocha doesn't have stub/mock functions. You should use some stub/mock library such as sinonjs.

E.g.

fetchSettings.ts:

interface MyDocment {}

export const fetchSettings = async (firestore): Promise<MyDocment> => {
  try {
    const response = await firestore.collection('someCollection').doc('someDoc').get();
    const data = response.data()!;
    return {
      dataOne: data.someDataOne,
      dataTwo: data.someDataTwo,
    };
  } catch (error) {
    console.log(error);
    return error;
  }
};

fetchSettings.test.ts:

import { fetchSettings } from './fetchSettings';
import sinon from 'sinon';

describe('66868604', () => {
  it('should return data', async () => {
    const mData = {
      someDataOne: 'someDataOne',
      someDataTwo: 'someDataTwo',
    };
    const mRes = { data: sinon.stub().returns(mData) };
    const mFirestore = {
      collection: sinon.stub().returnsThis(),
      doc: sinon.stub().returnsThis(),
      get: sinon.stub().resolves(mRes),
    };
    const actual = await fetchSettings(mFirestore);
    sinon.assert.match(actual, { dataOne: 'someDataOne', dataTwo: 'someDataTwo' });
    sinon.assert.calledWithExactly(mFirestore.collection, 'someCollection');
    sinon.assert.calledWithExactly(mFirestore.doc, 'someDoc');
    sinon.assert.calledOnce(mFirestore.get);
    sinon.assert.calledOnce(mRes.data);
  });

  it('should handle error', async () => {
    const mErr = new Error('stackoverflow');
    const mFirestore = {
      collection: sinon.stub().returnsThis(),
      doc: sinon.stub().returnsThis(),
      get: sinon.stub().rejects(mErr),
    };
    const actual = await fetchSettings(mFirestore);
    sinon.assert.match(actual, mErr);
    sinon.assert.calledWithExactly(mFirestore.collection, 'someCollection');
    sinon.assert.calledWithExactly(mFirestore.doc, 'someDoc');
    sinon.assert.calledOnce(mFirestore.get);
  });
});

unit test result:

  66868604
    ✓ should return data
Error: stackoverflow
    at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/66868604/fetchSettings.test.ts:25:18
    at Generator.next (<anonymous>)
    at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/66868604/fetchSettings.test.ts:8:71
    at new Promise (<anonymous>)
    at __awaiter (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/66868604/fetchSettings.test.ts:4:12)
    at Context.<anonymous> (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/66868604/fetchSettings.test.ts:24:40)
    at callFn (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runnable.js:364:21)
    at Test.Runnable.run (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runnable.js:352:5)
    at Runner.runTest (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:677:10)
    at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:801:12
    at next (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:594:14)
    at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:604:7
    at next (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:486:14)
    at Immediate.<anonymous> (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:572:5)
    at processImmediate (internal/timers.js:461:21)
    ✓ should handle error


  2 passing (10ms)

------------------|---------|----------|---------|---------|-------------------
File              | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------------|---------|----------|---------|---------|-------------------
All files         |     100 |      100 |     100 |     100 |                   
 fetchSettings.ts |     100 |      100 |     100 |     100 |                   
------------------|---------|----------|---------|---------|-------------------

Upvotes: 1

lifeisfoo
lifeisfoo

Reputation: 16294

Mocha doesn't include a mock library, so you need to choose one and add it manually to your tests.

Install sinon with

npm install sinon

Then include it in your code:

const sinon = require("sinon");

And use a stub to create you function:

Test stubs are functions (spies) with pre-programmed behavior.

// create an anonymous function stub
const stub = sinon.stub();
// set the resolved value (you want a promise)
stub.resolves({dataOne:'somedata', dataTwo:'someotherdata'});
// use returns if you want a plain function
// stub.returns(obj);

Now you can call stub() as your function.

You can also use fakes or mocks to achieve the same result.

Please take a look to the setup documentation to avoid common issues.

Upvotes: 1

Related Questions