到目前为止,我有 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
是一个异步函数。在实际建立连接之前,该函数返回并且 Node.js 继续运行。
Mongoose 为大多数异步函数返回承诺。与 using 类似done
,mocha 支持等待承诺解决/拒绝开箱即用。只要 promise 是return
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();
});
});
});
mocha 也使用this
for 配置,因此避免在 mocha 定义中使用箭头函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句