到目前为止,我有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定义。

10-07 13:04
查看更多