vendredi 17 janvier 2020

Getting trouble on writing test cases for Nodejs app

Please help me, I am currently having a task to write the integration test for my Node.js app, but I cannot get the instance of the server to stimulate the request.

Here is the server configuration code

// server.js
const {
    app,
} = require('./config/express');

const {
    connect,
} = require('./config/mongo');

const {
    port,
} = require('./config/vars');

(async function () {
    const connection = await connect();
    const db = connection.db;

    app.locals.db = db;

    app.listen(port, () => {
        console.log(`Server is listening on port: ${port}`);
    });
})();

module.exports = {
    app,
};

The anonymous function above have to be wrapped in an async because the database connection connect is an async function

// config/mongodb.js
...

module.exports.connect = async () => {
    try {
        const client = await MongoClient.connect(uri, options);
        console.log('Database connection established');

        const db = client.db(name);

        return {
            db,
            client,
        };
    } catch (error) {
        console.log('Error connecting to MongoDb');
        process.exit(0);
    }
};
...

Then, this is how the connection instance of database is used in Model and Controller.

// model/index.js
class Model {
    constructor({ db }) {
        this.User = new User(db);
        this.video = new Video(db);
        this.RefreshToken = new RefreshToken(db);
    }
}
module.exports = Model;

// model/user.model.js
class User {
    /**
     * Create new User instance
     * @param {object} collection MongoDb user collection instance
     */
    constructor(db) {
        this.collection = db.collection('user');
}
// controller/index.js
...
const { db } = req.app.locals;
const { User } = new Model({ db });
...

This configuration works well when I run the server, but it is not working properly in testing environment, this is the result of an integration test case that I wrote

text: `{"code":500,"message":"Cannot read property 'collection' of undefined"}`,

I know the reason here is because the app in server.js is exported before the database instance is assigned to the app.locals.db, but I don't know how to re-work with the configuration file, anyone can help me?

Aucun commentaire:

Enregistrer un commentaire