【问题标题】:Mocha test successfully connecting to my database but not saving instancesMocha 测试成功连接到我的数据库但未保存实例
【发布时间】:2018-02-02 21:58:31
【问题描述】:

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/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);
    });

test/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 中保存一个实例时,它就可以工作了。有什么建议吗?

【问题讨论】:

    标签: javascript node.js mongodb mongoose mocha.js


    【解决方案1】:

    这是因为猫鼬打开连接之后测试正在运行。您需要使用 before 钩子来保证连接已打开。

    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);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 2018-09-22
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多