使用 mocha 和 request 测试 mongodb 数据库

Testing mongodb database with mocha and request

我有 2 个问题,到目前为止,我正在寻找答案 3 天,但无法弄清楚。
1.测试时应该什么时候连接数据库?
2. 我在运行 测试时总是报错: { "before each" hook for "should list all books on /book GET" } 并且还没有找到解决方案或确切原因。我究竟做错了什么?到目前为止,我唯一的答案是不要在 beforeEach() 中调用 done() 两次,但我没有这样做...

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();
        });
    });
});

mongoose.createConnection 是一个异步函数。在实际建立连接之前,函数 returns 和 Node.js 继续。

Mongoose returns 承诺大多数异步函数。与使用 done 类似,mocha 支持开箱即用地等待对 resolve/reject 的承诺。只要承诺是 mocha 函数的 return 值。

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();
        });
    });
});

此外,mocha 使用 this 进行配置,因此请避免对 mocha 定义使用箭头函数。