如何用 mocha 模拟 firestore

How to mock firestore with mocha

我有一个简单的包装函数,它 return 是来自 firestore 的特定文档,如下所示:

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;
    }
};

这个函数用在我想测试的其他函数中,因此我想模拟 firestore 到 return 一个特定的文档,这个实现的确切方式。

如何使用 mocha 执行此操作?开个玩笑,我可以有类似 jest.fn(()=>Promise.resolve({dataOne:'somedata', dataTwo:'someotherdata'}));

的东西

mocha 的方法是什么?

Mocha 不包含模拟库,因此您需要 choose one 并将其手动添加到您的测试中。

安装 sinon

npm install sinon

然后将其包含在您的代码中:

const sinon = require("sinon");

并使用 stub 创建函数:

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);

现在您可以调用 stub() 作为您的函数。

您也可以使用 fakes or mocks 来获得相同的结果。

请查看 setup documentation 以避免常见问题。

Mocha 没有 stub/mock 函数。您应该使用一些 stub/mock 库,例如 sinonjs.

例如

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('Whosebug');
    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);
  });
});

单元测试结果:

  66868604
    ✓ should return data
Error: Whosebug
    at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/Whosebug/66868604/fetchSettings.test.ts:25:18
    at Generator.next (<anonymous>)
    at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/Whosebug/66868604/fetchSettings.test.ts:8:71
    at new Promise (<anonymous>)
    at __awaiter (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/Whosebug/66868604/fetchSettings.test.ts:4:12)
    at Context.<anonymous> (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/Whosebug/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 |                   
------------------|---------|----------|---------|---------|-------------------