Node.js: exporting class / prototype versus instance

Since I execute most of my programs in Java, I find it is forced to export the class to a Node.js module instead of an object instance, like this:

class Connection {
    constructor(db) {
        this.db = db;
    }
    connect(connectionString) {
        this.db.connect(connectionString);
    }
}
exports.Connection = Connection;

      

Since this would require instantiating the class multiple times through the dependent modules, I still need to export the already existing instance for use in the rest of the production code. I am doing this in the same module:

exports.connection = new Connection(require("mongoose"));

      

This allows you to check how the real dependency can be replaced in the test:

const Connection = require("./connection").Connection;

describe("Connection", () => {
    it("connects to a db", () => {
        const connection = new Connection({connect: () => {}});
        // ...
    });
});

      

This approach works, but it has a weird feeling as I am mixing two patterns here: prototype export (for unit tests) and instance (for production code). It is acceptable? Should I continue this or change something else? If so, what is the preferred pattern?

+3


source to share





All Articles