Warm tip: This article is reproduced from serverfault.com, please click

Nodejs Expressjs Mongodb Javascript Unit Test Using Mocha Chai Sinon for random Nodejs Project

发布于 2020-11-25 07:05:53

Can somebody show me how to do "unit test" for this sample project for function homeDog? i have following sample function that from random project that i wish to try add unit test for it while i learn how to do unit test using Mocha Chai Sinon the sample random Nodejs Project that referencing is from https://github.com/seanaharrison/node-express-mongodb-example.

I was struggling to make a unit test for homeDog function, but then i face issues and can somebody kindly show me a working unit test on how to make a unit test for function homeDog for me to have a starting point?

And here is what i tried but failed.

what_i_had_done_but_failed

exports.homeDog = function(req, res) {
    var db = req.db;
    var collection = db.collection('dogs');
    collection.find().toArray(function(err, dogsArray) {
        if (dogsArray) {
            res.render('index', {
                title: 'Dogs',
                path: req.path,
                dogs: dogsArray
            });
        }
        else {
            res.render('index', {
                title: 'No Dogs Found'
            });
        }
    });
};
Questioner
Tan Wll
Viewed
0
199 2020-11-27 15:21:44

Since you need a "mock database" but you don't use it in your code (I think) I'll try to explain how to test an API project with a mock database.

That is: You don't need a real DB to test your API, you need an "in-memory DB" created and closed in every execution of your tests.

First of all is install a mock dependency like mongo-mock, mongodb-memory-server or whatever you want.

Personally, I use mongodb-memory-server.

So following the docs you can set up your project. I have my mockDB.js file at the same level as test.js.

mockDB.jsfile should include something like this (this code can change if you use another package.):

const { MongoMemoryServer } = require('mongodb-memory-server');
const mongod = new MongoMemoryServer();

module.exports.connect = async () => {
    const uri = await mongod.getUri();

    const mongooseOpts = {
        useNewUrlParser: true,
        useFindAndModify: false,
        useUnifiedTopology: true 
    };

    await mongoose.connect(uri, mongooseOpts);
}

Then, you have a file where your mock DB will be initialized and connected. At this point, my mongo DB is initialized. I'm using mongoose but another option is allowed to.

The controller (homeDog in this case I think) file doesn't matter here because you are testing the controller so the code has to be the same that will be in production. The controller is the code to test, so it should not be modified for tests purposes.

The last file is test.js. In this file, you have to import your mockDB.js file and start de database.

const mockDB = require('./mockDB');

... 

before(async () => await mockDB.connect());

In this way, you can execute your tests and the controller will execute queries to memory database. Also, you can use your file mockDB.js to implement auxiliary queries.

For example, to get a specific value from a field you can create a method like

module.exports.findValueById(id) => {
  //return result
}

And into your test file call this module:

var idFound = mockDB.findValueById(id)

Using this you can, for example, query the database after inserting a document and check if the collection is ok. Or check if an update has been made correctly or whatever you want.

If your function is a GET you only need to compare the data returned by homeDog with the existing "mock DB".