To mock a Mongoose
Setting up can take a while sometimes so I decided to give a different approach a go this time round. I have created a simple grunt-init template which will do most of the grunt work for us (such pun!). Install grunt-init globally with
npm i -g grunt-init if you don’t already have it. To use the template, simply clone it into your ~/.grunt-init/ directory (creating the directory if need be):
~$ mkdir .grunt-init && cd .grunt-init
Automation time - simply cd into an empty directory and type the magic words:
to-mock-a-mongoose$ grunt-init mongoose-blog-template-1
What have we got here?
First off, install mocha globally if you don’t already have it:
npm i -g mocha and run
Open up model/db.js. This is where we’re establishing our db connection (and registering some event handlers). The connection will actually be mocked out in our test/test.js. That’s pretty useful. Now we don’t need MongoDB to be running to make some assertions on our code, code that would normally be interacting with the database.
To get the mocking done right, make sure you mock Mongoose before setting it up:
var mockgoose = require('mockgoose');
model/item.js defines the structure (the schema) of an Item document which we’d like to store in our db. We’re also creating a model from our schema. This is basically a constructor we can use to create Item objects which will map to documents in our db. i.e. instances created from our Item model will be important to us if we care about interacting with our db.
test/test.js, after mocking our Mongoose, simply requires and makes use.
// code abbreviated... see generated test.js