how to integration test nodeJS mongo how to integration test nodeJS mongo mongoose mongoose

how to integration test nodeJS mongo


Considering Setting is a mongoose model you would have this at the end of the model file

setting.js...module.exports = mongoose.model('Setting', settingSchema)

And I think if you require this model in your test file like this

test.jsvar Setting = require('./setting')

Then you could call Setting.findOne instead of mongoose.Setting.findOne inside the actual test case and it should work fine. Also you should make sure you have successfully connected to your test database before you do this. It is a good practice to clean the tested collection in a before hook

before(function(done) {    // Connect to database here    Setting.remove({}, function(err) {        if (err)            throw err        else            done()    })})

and do the same thing afterEach test case.

I don't see where and how you use supertest in your snippet but I believe it is the right tool. Again, in your before hook you could first call request = request(require('./app')) where app.js exports your express application. Moreover, you could move the code that connects to the database to your app.js, which feels more environment-independent.


Before writing unit and integration test, you should install required libraries

  1. Install mocha framework globally

    sudo npm install -g mocha
  2. Install chai assertion library and HTTP plug-in

    npm install chainpm install chai-http
  3. Add mocha command to your package.json file

    "scripts": {  "test": "mocha",  "start": "nodemon app.js" }

Usage of mocha framework and chai assertion library can be seen in code below

const chai = require('chai');const chaiHttp = require('chai-http');chai.should();chai.use(chaiHttp);describe("Integration Test Case 1",() => {it("Sign Up-In", () => {    // Sign Up    chai.request("localhost:5000/api/users")        .post("/signup")        .send(createdUser)        .end(async (error, response) => {            await response.should.have.status(201);            // Sign In            chai.request("localhost:5000/api/users")                .get("/signin")                .send(userCredential)                .end(async (error, response) => {                    await response.should.have.status(202);}};