Skip to content

Instantly share code, notes, and snippets.

@hellboy81
Created October 27, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hellboy81/06eb32ccb3d9a4bd7a6c to your computer and use it in GitHub Desktop.
Save hellboy81/06eb32ccb3d9a4bd7a6c to your computer and use it in GitHub Desktop.
Piping to CouchDB Attachment
// file is input ReadStream that should be saved to CouchDB attachment
// See description: http://git.io/vWMZ9
// See API : http://docs.couchdb.org/en/1.6.1/api/document/attachments.html#put--db-docid-attname
var attachment = db.attachment.insert('new', 'rab.png', null, 'image/png', { rev: '12-150985a725ec88be471921a54ce91452' })
// Handle file reading error
file.on('error', function (err) {
return cb(err)
})
// Handle attachment writting error
// Lost connection with CoucDB ???
attachment.on('error', function (err) {
return cb(err)
})
// As in [Professional Node.js](https://goo.gl/ijN1js) written
// Client should get response in on('end') event for attachment
// Isn't it?
attachment.on('end', function () {
return cb()
})
file.pipe(attachment)
@hellboy81
Copy link
Author

// Test case
// Arrange phase

// As I mentioned both file and attachment stream
// In test should not be stubbed with EventEmitter 
// All stubs should be created manually

// Create stub for file stream
// Only pipe method should be stubbed
var file = {
   pipe: sinon.stub()
}

// Create stub for attachment  output write stream
var attachment = {
   on: sinon.stub() // Only events should be stubbed
}

// Simulate on end event - attachment uploaded successfully
// attachment.emit('end')
attachment.on.withArgs('end').yields()

// Make stub for db.attachment.insert
// that returns previous attachment
db = {
   attachment: {
      insert: sinon.stub()
   }
}

db.attachment.insert.returns(attachment)

// Inject dependncy into sut
mySUTMod.__set__('db', db)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment