的src / user.js的
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
const UserSchema = new Schema({
name : String
});
const User = mongoose.model('user', UserSchema);
module.exports = User;
测试/ test_helper.js
// DO SOME INITIAL SETUP FOR TEST
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', { useMongoClient : true });
mongoose.Promise = global.Promise;
mongoose.connection
.once('open', ()=> console.log('Good to go'))
.on('error',(error)=> {
console.warn('Warning',error);
});
测试/ create_test.js
const assert = require('assert');
const User = require('../src/user');
const mongoose = require('mongoose');
describe('Creating records', () => {
it('saves a user', () => {
const joe = new User({ name : 'Joe' });
joe.save();
});
});
当我尝试在create_test.js中保存实例时,它不会将其保存在数据库中。但是当我在test_helper.js文件中保存一个实例时,它正在工作。有什么建议吗?
答案 0 :(得分:0)
这是因为mongoose在之后打开了连接,测试正在运行。您需要在挂钩之前使用以确保连接已打开。
twilio