我有 2 个问题,到目前为止我已经寻找答案 3 天但无法解决。
1. 测试时什么时候连接数据库?
2. 运行测试时我总是遇到错误: { "before every"hook for "should list all books on/book GET"} 并且尚未找到解决方案或确切原因。我究竟做错了什么?到目前为止,我唯一的答案是不要在 beforeEach() 中调用 did() 两次,但我没有这样做......
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 在实际建立连接之前继续运行。
Mongoose 返回大多数异步函数的 promise 。与使用 done
类似,mocha 支持等待 Promise 立即解析/拒绝。只要 promise 是 mocha 函数的返回
值即可。
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();
});
});
});
摩卡还使用 this
进行配置,因此避免在摩卡定义中使用箭头函数。
关于node.js - 使用 mocha 和 request 测试 mongodb 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47570972/