繁体   English   中英

使用Mocha和Request测试MongoDB数据库

[英]Testing mongodb database with mocha and request

到目前为止,我有2个问题正在寻找答案,为期3天,无法解决。
1.我何时应该在测试时连接到数据库?
2.运行测试时,我总是会出错:{“在每个钩子之前,”钩子应该列出/ 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是一个异步函数。 该函数返回并且Node.js在实际建立连接之前继续运行。

猫鼬返回大多数异步函数的承诺。 与使用done相似,mocha支持开箱即用地解决承诺。 只要promise是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定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM