Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure for unit testing on node.js with mongoose

I've been developing with node.js for months but now I'm starting a new project and I'd like to know how to structure the app.

My problem comes when talking about unit testing. I will use nodeunit to write unit tests.

Also I'm using express to define my REST routes.

I was thinking about writing my code that access databases in two "separate" files (They will be more, obviously, but I'm just trying to simplify the code). There will be the routes code.

var mongoose = require('mongoose')
 , itemsService = require('./../../lib/services/items-service');

// GET '/items'
exports.list = function(req, res) {
    itemsService.findAll({
        start: req.query.start,
        size: req.query.size,
        cb: function(offers) {
            res.json(offers);
        }
   });  
  };

And, as I'm using there, an item service used just to access data layer. I'm doing this to test only data access layer on unit testing. It'll be something like this:

var mongoose = require('mongoose')
  , Item = require('./../mongoose-models').Item;

exports.findAll = function(options) {
    var query = Offer
        .find({});
    if (options.start && options.size) {
        query
            .limit(size)
            .skip(start)
    }
    query.exec(function(err, offers) {
        if (!err) {
                options.cb(offers);
            }
    })
};

This way I can check with unit testing if it works correctly and I can use this code everywhere I want. The only thing I'm not sure if it's been correctly done is the way I pass a callback function to use returned value.

What do you think?

Thanks!

like image 281
Javier Manzano Avatar asked Dec 27 '12 14:12

Javier Manzano


People also ask

What defines the structure of documents in Mongoose?

A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

Which testing framework is best for Node JS?

What are the best Node. js unit testing frameworks? According to “The State of JavaScript 2021,” the most popular JavaScript testing frameworks and libraries in 2021 were Testing Library, Vitest, Jest, Cypress, Playwright, and Storybook. Rounding out the top ten are Puppeteer, Mocha, Jasmine, AVA, and WebdriverIO.

Is Mongoose an ORM or ODM?

Mongoose is an ODM that provides a straightforward and schema-based solution to model your application data on top of MongoDB's native drivers.


1 Answers

Yes, quite easily! You can use a unit testing module like mocha and either node's own assert or another such as should.

As an example of a test case for your example model:

var ItemService = require('../../lib/services/items-service');
var should = require('should');
var mongoose = require('mongoose');

// We need a database connection
mongoose.connect('mongodb://localhost/project-db-test');

// Now we write specs using the mocha BDD api
describe('ItemService', function() {

  describe('#findAll( options )', function() {

    it('"args.size" returns the correct length', function( done ) { // Async test, the lone argument is the complete callback
      var _size = Math.round(Math.random() * 420));
      ItemService.findAll({
        size : _size,
        cb : function( result ) {
          should.exist(result);
          result.length.should.equal(_size);
          // etc.

          done(); // We call async test complete method
        }
      }, 
    });


    it('does something else...', function() {

    });

  });

});

And so on, ad nauseum.

Then when you're done writing your tests - assuming you've $ npm install mocha'd - then you'd simply run $ ./node_modules/.bin/mocha or $ mocha if you used npm's -g flag.

Depends how rectal/detailed you want to be really. I've always been advised to, and find it easier to: Write the tests first, to get a clear specification perspective. Then write the implementation against the tests, with any extra insight a freebie.

like image 65
rounce Avatar answered Oct 08 '22 06:10

rounce