title: Stubbing S3 uploads in Node.js
body: <p>How would I go about stubbing S3 uploads in Node.js?</p>
  
  <p>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:</p>
  
  <pre><code>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
  });
  </code></pre>
  
  <p>If I try to stub <code>AWS.S3</code> or <code>AWS.S3.prototype</code>, nothing changes. I assume this is because my tests have required <code>aws-sdk</code> themselves and have their own copy of each function.</p>
  
  <p>My test looks like this:</p>
  
  <pre><code>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();
      });
    });
  });
  </code></pre>
  
  <p>This test works fine, but it does not stub the upload to S3, so the upload actually goes through :X.</p>