2017-08-24 62 views
0

的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

這是因爲貓鼬打開後連接,測試運行。您需要使用掛鉤,以保證連接打開。

before(done => { 
    mongoose.connect('mongodb://localhost/test', { useMongoClient : true }); 
    mongoose.Promise = global.Promise; 

    mongoose.connection 
    .once('open',() => done()) 
    .on('error', err => console.err('Db connection error', err); 
    }); 
}); 
相關問題