在Node.js中存根S3上传 [英] Stubbing S3 uploads in Node.js
问题描述
我该如何在Node.js中存根S3上传?
How would I go about stubbing S3 uploads in Node.js?
为了获得见识,我正在使用Mocha进行测试,并使用Sinon进行存根,但是我愿意改变任何东西.我有一个导出执行上传功能的文件.看起来像这样:
For insight, I'm using Mocha for tests and Sinon for stubbing, but I'm open to changing anything. I have a file that exports a function that performs the upload. It looks like this:
var AWS = require('aws-sdk');
var s3 = new AWS.S3({ params: { Bucket: process.env.S3_BUCKET }});
var params = { Key: key, Body: body };
s3.upload(params, function (error, data) {
// Handle upload or error
});
如果我尝试对 AWS.S3
或 AWS.S3.prototype
进行存根,则没有任何变化.我认为这是因为我的测试本身需要 aws-sdk
,并且每个函数都有自己的副本.
If I try to stub AWS.S3
or AWS.S3.prototype
, nothing changes. I assume this is because my tests have required aws-sdk
themselves and have their own copy of each function.
我的测试如下:
describe('POST /files', function () {
var url = baseURL + '/files';
it('uploads the file to s3', function (done) {
var fs = require('fs');
var formData = {
video: fs.createReadStream(process.cwd() + '/test/support/video.mp4')
};
var params = {url: url, formData: formData};
request.post(params, function (error, response, body) {
expect(response.statusCode).to.eq(200);
expect(response.body).to.eq('Uploaded');
done();
});
});
});
此测试工作正常,但不会对上传到S3的存根进行存根,因此上传实际上是通过:X进行的.
This test works fine, but it does not stub the upload to S3, so the upload actually goes through :X.
推荐答案
s3UploadStub = AWS.S3.prototype.upload = sandbox.stub();
it("should upload successfully", async function() {
s3UploadStub.yields(null, data);
let response = await FileUtil.uploadFile(fileReference,data);
expect(s3UploadStub.calledOnce).to.be.true;
expect(response.statusCode).to.equal(200);
expect(response.body).to.equal(fileReference);
});
这篇关于在Node.js中存根S3上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!