如何使用 sinon 模拟 AWS S3 getObject



我正在尝试对从存储桶返回 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"
}
);

最新更新