如何使用带有 sinon TDD 的 mocha & chai 来测试 class 是否被调用?

How to test class called or not using mocha & chai with sinon TDD?

我想用 sinon 在 nodejs、mocha 和 chai 中测试 class 调用与否。我尝试使用存根,但没有达到我预期的效果。

someMiddleware.js

module.export.someMiddleware = async(req,res,next)=>{
const responseData = await someReturnFunction(req);

if (!responseData || responseData == null) { 
      throw new SomeExtendedErrrorClass("stringArg");
    }
res.send(responseData);
}

testFile.js

sinon
      .stub(someMiddleWare , "someReturnFunction")
      .returns(null);
    const stubClass = sinon.stub(SomeExtendedErrrorClass, "constructor");
    someMiddleware(req, res, next);
    expect(stubClass).to.have.be.called;

即使调用了 SomeExtendedErrrorClass,也未检测到 sinon。

Sinon 不支持存根独立函数或 class 从其他模块导入。您需要使用 Link Seams, we will be using proxyquire 来构造我们的接缝。

例如

someMiddleware.js:

const someReturnFunction = require('./someReturnFunction');
const SomeExtendedErrrorClass = require('./SomeExtendedErrrorClass');

module.exports.someMiddleware = async (req, res, next) => {
  const responseData = await someReturnFunction(req);

  if (!responseData || responseData == null) {
    throw new SomeExtendedErrrorClass('stringArg');
  }
  res.send(responseData);
};

SomeExtendedErrrorClass.js:

class SomeExtendedErrrorClass extends Error {}

someReturnFunction.js:

async function someReturnFunction() {
  return 'real implementation';
}

someMiddleware.test.js:

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const proxyquire = require('proxyquire');
const sinon = require('sinon');
const SomeExtendedErrrorClass = require('./SomeExtendedErrrorClass');

chai.use(chaiAsPromised);
const { expect } = chai;

describe('68640048', () => {
  it('should get and send response data', async () => {
    const someReturnFunctionStub = sinon.stub().resolves('teresa teng');

    const { someMiddleware } = proxyquire('./someMiddleware', {
      './someReturnFunction': someReturnFunctionStub,
    });
    const mReq = {};
    const mRes = { send: sinon.stub() };
    await someMiddleware(mReq, mRes);
    sinon.assert.calledWithExactly(mRes.send, 'teresa teng');
  });

  it('should throw error', async () => {
    const someReturnFunctionStub = sinon.stub().resolves(null);
    const { someMiddleware } = proxyquire('./someMiddleware', {
      './someReturnFunction': someReturnFunctionStub,
    });

    const mReq = {};
    const mRes = { send: sinon.stub() };
    await expect(someMiddleware(mReq, mRes)).to.eventually.rejectedWith(SomeExtendedErrrorClass);
  });
});

测试结果:

  68640048
    ✓ should get and send response data
    ✓ should throw error


  2 passing (10ms)