[Node.js] Stubbing Mongoose virtual attributes with sinon

Tadashi Shigeoka ·  Tue, July 7, 2015

I’ll introduce how to stub Mongoose virtual attributes with sinon.

mongoose | マングース

First, assume that a Product model like the following is defined.

# define Mongoose Product model
mongoose = require 'mongoose'

productSchema = new mongoose.Schema({
  # something
})

productSchema.virtual('discountPercentage').get ()->
  # calculate discountPercentage
  return discountPercentage

Product = mongoose.model 'Product', productSchema

And the test code to stub the discountPercentage virtual looks like this:

# in test code
sinon = require 'sinon'

product = new Product()

console.log product.discountPercentage
# returns the calculation result of discountPercentage virtual

stub = sinon.stub product, 'get'
stub.withArgs('discountPercentage').returns 50

console.log product.discountPercentage
# always returns 50

# don't forget to restore when done
stub.restore()

The key points are sinon.stub mongooseInstance, ‘get’ and stub.withArgs(‘virtualName’).returns where you’re stubbing the return value of virtualName.

Reference Information

That’s all from the Gemba.