ColdMonkey
ColdMonkey

Reputation: 57

Testing Mongoose model required properties

I recently started developing apps with node.js, express, and mongoose. I decided to use mocha as a testing framework and is wondering how would I unit test mongoose.model properties for validity.

So if I had a model defined like this:

var userSchema = new Schema({
    name: {type: String, required: true}
});

var userModel = new mongoose.model('User', userSchema);

I'm assuming that stating "require: true" means that userSchema.name must be defined and not null.

How do I test that when I instantiate a userModel, I must provide it with an object containing a name property that is not null or undefined?

Thanks

Upvotes: 0

Views: 845

Answers (1)

forrert
forrert

Reputation: 4239

Check out Mockgoose for writing unit tests with mongoose models without the need to have a mongodb instance running.

You could write a simple test like this:

    var mongoose = require('mongoose'),
        mockgoose = require('mockgoose');

    mockgoose(mongoose);

    var Schema = mongoose.Schema;
    var SimpleSchema = new Schema({
        name: {
            type: String,
            required: true
        }
    });
    mongoose.model('SimpleModel', SimpleSchema);

    it('fails to save document with missing name', function(done) {
        var simpleModel = new SimpleModel({
            name: undefined
        });
        simpleModel.save(function(err) {
            should.exist(err);
            done();
        });
    });

Then define different tests with different values for name (null, undefined, etc.) or even an empty object (i.e. an object without name property).

Upvotes: 1

Related Questions