vendredi 19 août 2016

mocha --watch and mongoose models

If I leave mocha watching for changes, every time I save a file mongoose throws the following error:

OverwriteModelError: Cannot overwrite Client model once compiled

I know that mongoose won't allow to define a model twice, but I don't know how to make it work with mocha --watch.

// client.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var clientSchema = new Schema({
    secret: { type: String, required: true, unique: true },
    name: String,
    description: String,
    grant_types: [String],
    created_at: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Client', clientSchema);

And here is the test

// client-test.js
var chai = require('chai');
var chaiHttp = require('chai-http');
var mongoose = require('mongoose');

var server = require('../../app');
var Client = require('../../auth/models').Client;

var should = chai.should();

chai.use(chaiHttp);

describe('client endpoints', function() {
    after(function(done) {
        mongoose.connection.close();
        done();
    });

    it('should get a single client on /auth/client/{clientId} GET', function(done) {
        var clt = new Client({
            name: 'my app name',
            description: 'super usefull and nice app',
            grant_types: ['password', 'refresh_token']
        });

        clt.save(function(err) {
            chai.request(server)
                .get('/auth/client/' + clt._id.toString())
                .end(function(err, res) {
                    res.should.have.status(200);
                    res.should.be.json;
                    res.body.should.have.property('client_id');
                    res.body.should.not.have.property('secret');
                    res.body.should.have.property('name');
                    res.body.should.have.property('description');
                    done();
                });
        });
    });
});

Aucun commentaire:

Enregistrer un commentaire