vendredi 9 novembre 2018

Mongoose Plugin Integration Test

I'm trying to test the functionality of a mongoose plugin. But when I save an "any" model that implements the plugin, I never get a response from the promise to save.

I tried to increase the mocha timeout --timeout 500000 to see if I throw some error, but always ends up releasing the same mocha timeout error. I think that when I create the model during the test, it doesn't connect to the BD because if I do it with an imported model this error doesn't occur, but from a test point of view I shouldn't use logic models and try to make it as similar as possible to an integration test.

Plugin code:

module.exports.myPlugin = (schema, options) => {

const mySchema = {
    someField: {
        type: mongoose.SchemaTypes.String,
    }
};
mySchema[options.fieldName] = [OrderLine.obj];
schema.add(mySchema);

const someFunction = function (orderLines) {
    // TODO: Important things.
};

schema.pre('save', function (next) {
    this.someField = someFunction();
});

schema.pre('update', function (next) {
    this.someField = someFunction();
});

};

Test Code:

import {myPlugin} from "../../../api/core/plugins";

const chai = require('chai');
const sinonChai = require("sinon-chai");
const chaiAsPromised = require('chai-as-promised');
const expect = chai.expect;
chai.use(chaiAsPromised);
chai.use(sinonChai);

const mongoose = require('mongoose');

const MONGO_URL = 'mongodb://username:password@127.0.0.1:27017/develop?authSource=admin';


describe('Test some important plugin', () => {

    let db;
    let ModelTest;

    before((done) => {

        mongoose.connect(MONGO_URL, {useNewUrlParser: true});
        db = mongoose.connection;
        db.on('error', console.error.bind(console, 'connection error:'));
        db.once('open', function callback () {
            const modelTestSchema = new mongoose.Schema({
                name: {
                    type: mongoose.SchemaTypes.String
                },
            });
            modelTestSchema.plugin(myPlugin, {fieldName: 'customField'});
            ModelTest = mongoose.model('ModelTest', modelTestSchema);
            done();
        });

    });

    after(function (done) {
        db.close();
        done();
    });

    it('should execute some important logic', function () {

        let model = new ModelTest({
            customField: 'my custom field value',
            name: 'test model name'
        });
        try {
            let promise = model.save();
            return Promise.all([
                expect(promise).to.eventually.be.fulfilled,
            ]);
        } catch (e) {
            console.log(e);
            return e;
        }
    });

});

Aucun commentaire:

Enregistrer un commentaire