AlinP25
AlinP25

Reputation: 95

Testing mongodb database with mocha and request

I've got 2 questions that I am searching for an answer for 3 days so far and can't figure it out.
1. When I should connect to the database when testing?
2. I always get an error when running the test: { "before each" hook for "should list all books on /book GET" } and haven't yet found a solution or the exact cause for it. What am I doing wrong? The only answer I have so far is not to call done() twice in beforeEach() but I ain't doing it...

var chai      = require('chai'),
    expect    = chai.expect,
    request   = require('request'), 
    mongoose  = require('mongoose'),
    Book      = require('./../models/book');
// book = require('../model')

mongoose.createConnection('mongodb://localhost/books');

describe('Testing the routes', () => {
    beforeEach((done) => {
        Book.remove({}, (err) => {
            if (err) {
                console.log(err);
            }
        });
        var newBook = new Book();
        newBook.title  = "Lord Of The Rings";
        newBook.author = "J. R. R. Tolkien";
        newBook.pages  = 1234;
        newBook.year   = 2000;
        newBook.save((err) => {
            if (err) {
                console.log(err);
            }
            done();
        });
    });

    it('should list all books on /book GET', (done) => {
        var url = 'http://localhost:8080/book';
        request.get(url, (error, response, body) => {
            expect(body).to.be.an('array');
            expect(body.length).to.equal(1);
            done();
        });
    });
});

Upvotes: 0

Views: 5876

Answers (1)

Matt
Matt

Reputation: 74680

mongoose.createConnection is an asynchronous function. The function returns and Node.js continues on before the connection is actually established.

Mongoose returns promises for most asynchronous functions. Similar to using done, mocha supports waiting for promises to resolve/reject out of the box. As long as the promise is the return value to the mocha function.

describe('Testing the routes', function(){

    before('connect', function(){
        return mongoose.createConnection('mongodb://localhost/books')
    })

    beforeEach(function(){
        return Book.remove({})
    })

    beforeEach(function(){
        var newBook = new Book();
        newBook.title  = "Lord Of The Rings";
        newBook.author = "J. R. R. Tolkien";
        newBook.pages  = 1234;
        newBook.year   = 2000;
        return newBook.save();
    });

    it('should list all books on /book GET', function(done){
        var url = 'http://localhost:8080/book';
        request.get(url, (error, response, body) => {
            if (error) done(error)
            expect(body).to.be.an('array');
            expect(body.length).to.equal(1);
            done();
        });
    });
});

Also mocha makes use of this for configuration so avoid using arrow functions for the mocha definitions.

Upvotes: 7

Related Questions