gpt4 book ai didi

javascript - 如何用 sinon 模拟 AWS S3 getObject

转载 作者:行者123 更新时间:2023-11-30 20:06:29 26 4
gpt4 key购买 nike

我正在尝试对从存储桶返回 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 构造函数,以便我可以 stub 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 文档后,我无法理解如何模拟构造函数,如何 stub 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, 错误, 数据);

关于javascript - 如何用 sinon 模拟 AWS S3 getObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52891128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com