[英]How to mock AWS S3 getObject with sinon
我正在尝试对从存储桶返回 S3 对象的 restify 路由进行单元测试
我的路线是:
module.exports = function(server) { server.get('/configs/:version', (req, res, next) => { const s3 = new AWS.S3(); const params = { Bucket: 'testBucket', Key: 'testKey' }; function send(data, next) { res.setHeader('Content-Type', 'text/plain'); res.setHeader('Cache-Control', 'no-cache'); res.status(200); res.send(data.Body); next(); } s3.getObject(params, (err, data) => (err) ? next(err) : send(data, next)); }); };
对于我的单元测试,我一直在尝试模拟 S3 构造函数,这样我就可以存根getObject
并惨遭失败。
describe('#configs', () => { let req; let res; let next; let server; let config; let AWS; let S3; let route; beforeEach(() => { req = { params: { version: 'testVersion' } }; res = { send: sinon.spy(), }; next = sinon.spy(); server = { get: sinon.stub(), }; config = { get: sinon.stub(), } AWS = () => { return { S3: () => { return { getObject: sinon.stub() } } } } route = proxyquire(process.cwd() + '/lib/routes/configs/get', { 'configs.js': config, 'aws-sdk': AWS, }); route(server); }); describe('#GET', () => { it('Should register configs get route', () => { let s3 = sinon.createStubInstance(AWS.S3, { getObject: sinon.stub(), }); server.get.callArgWith(1, req, res, next); expect(server.get).calledOnce.calledWith('/configs/:version'); expect(s3.getObject).calledOnce.calledWith({ Bucket: 'testBucket', Key: 'testKey' }); }); }); });
但是我收到这个错误: TypeError: undefined is not a spy or a call to a spy!
在 getObject 方法上。 一遍又一遍地阅读 sinon 文档后,我无法理解如何模拟构造函数,如何存根 getObject 方法,以便确保它被正确调用并返回,因此我知道它的响应得到了正确处理 有人可以帮忙吗我用这个?
终于让我的模拟工作了,问题是我将 AWS 模拟为一个没有对象的函数,需要将 S3 模拟为一个函数,因为需要实例化的是 S3。 模拟应该是这样的:
function S3() {
return s3;
}
s3 = {
getObject: sinon.stub(),
putObject: sinon.stub()
};
AWS = {
config: {
update: sinon.stub()
},
S3: S3
};
像这样,如果需要模拟 putObject,他只需要执行以下操作: s3.putObject.callsArgWith(1, err, data);
const getObjectStub = AWS.S3.prototype.getObject = Sinon.stub();
getObjectStub.yields(null, {
AcceptRanges: "bytes",
ContentLength: 3191,
ContentType: "image/jpeg",
Metadata: {
},
TagCount: 2,
VersionId: "null"
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.