lundi 24 décembre 2018

how do i test mongoDB database correctly

im getting into testing and i need to know what is the best way to test my database. I have put in a class. do i do both unit test and integration test on just integration tests for this. please provide advice and an example of how you would test.

im not even sure if this is a good way to setup your database. most people attach database calls to the route handler but i figured this way makes it easier to test the database so please give your input on that too.

thanks

import { MongoClient } from 'mongodb';



function Database(URI) {
    this.URI = URI;
    this.MONGO = MongoClient;

    // used defineProperty instead of normal method to prevent having to call collection
    Object.defineProperty(this, 'userCollection', {
        get: () => this.MONGO.db().collection(process.env.MONGO_USER_COLLECTION)
    })
}

Database.prototype.start = function () {
    this.MONGO = new this.MONGO(this.URI, { useNewUrlParser: true });
    return this;
};

Database.prototype.stop = function () {
    this.MONGO.shutdownServer();
};

Database.prototype.connect = async function (callback) {
    await this.MONGO.connect((error) => {
        if (error) return error;
        // linter expected a return value :S
        return callback();
    });
};

Database.prototype.createUser = function (data) {
    return this.userCollection.insertOne(data)
        .then(response => this.userCollection.find({ _id: response.insertedId })
            .limit(1)
            .next()
        );
};

// Database.prototype.deleteUser = function (userId) {
//     return this.userCollection.deleteOne({ _id: userId })
//         .then( deleteResult => {
                // (it might have changed to deleteResult.deletedCount)
//             if (deleteResult.result.n === 1) return { status: 'OK' };
//             return Error({status: 'Warning: object not found'});
//         });
// };

// Database.prototype.getUser = function (userId) {
//     return this.userCollection.find({ _id: userId })
//         .limit(1)
//         .next()
//         .then( user => {
//             if (!user) return { message: `No such issue: ${userId}` };
//             return user
//         })
// };

Aucun commentaire:

Enregistrer un commentaire