如何测试类叫或不使用摩卡和柴与sinon TDD?



我想测试类调用或不在nodejs, mocha &;和西侬一起喝咖啡。

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;

即使调用了someextendederrorclass,也没有检测到错误。

Sinon不支持存根独立函数或从其他模块导入的类。你需要使用链接接缝,我们将使用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)

相关内容

  • 没有找到相关文章

最新更新