【发布时间】:2019-09-25 01:20:03
【问题描述】:
我正在测试我的 express 应用,它使用Mongoose ORM 来处理 mongodb,但我在测试中遇到了一个小问题。
我尝试了以下方法:
const bcrypt = require('bcryptjs');
const { Schema, model } = require('mongoose');
const schema = new Schema({
password: String,
email: String,
}, {
timestamps: true
});
schema.pre('save', function (next) {
const admin = this;
if (admin.isModified('password')) {
admin.password = bcrypt.hashSync(admin.password, 8);
}
next();
});
schema.methods.verifyPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};
module.exports = model('Admin', schema);
连同以下配置的 mocha + chai 测试,用于启动 mocha 测试
process.env.DATABASE_URL = 'localhost:27017'
process.env.DATABASE_NAME = 'funtime'
process.env.NODE_ENV = 'test'
const chai = require('chai')
const chaiHttp = require('chai-http')
const chaiThings = require('chai-things')
const timekeeper = require('timekeeper')
const mongoose = require('mongoose')
chai.use(chaiThings)
chai.use(chaiHttp)
chai.should()
// Clearing DB function for beforeEach on tests
const clearDB = (callback) => {
console.log('clearing dbs...')
for (let i in mongoose.connection.collections) {
mongoose.connection.collections[i].deleteMany(() => {})
}
return
}
const now = new Date()
now.setHours(10)
now.setMinutes(0)
now.setSeconds(0)
now.setMilliseconds(0)
timekeeper.freeze(now)
require('./factory')
console.log('Tests starting...')
before(() => {
require('../lib/config/db')
})
after((done) => {
timekeeper.reset()
clearDB()
console.log('Tests done!')
done()
})
我正在使用 Docker 和 docker compose 来启动我的 express 服务器和 mongodb 实例,因此需要 env 变量。
在before(() => {}) 的行中,我需要我的db 配置,它具有以下内容:
const mongoose = require('mongoose');
const { mongoose: mongooseConfig } = require('./index');
const connectWithRetry = () => {
console.log('Retrying Mongodb connection');
mongoose.connect(mongooseConfig.uri, mongooseConfig.options)
.then(() => console.log('Connected to MongoDB...'))
.catch((err) => {
console.log(`Could not connect to MongoDB: ${err}:${err.stack}`);
setTimeout(connectWithRetry, 5000);
});
};
connectWithRetry();
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log('Mongoose default connection disconnected due to app termination');
process.exit(0);
});
});
当我运行命令./node_modules/.bin/mocha \"./tests/**/*.js\" --timeout 10000 --exit时,我收到的错误是这样的:
Invalid schema configuration: `FakeDate` is not a valid type at path `updatedAt`.
不知道这里出了什么问题
编辑(已解决)
通过删除timekeeper,问题得到解决。感谢@jeffheifetz 的评论和帮助!
【问题讨论】:
-
我只是猜测,但
FakeDate很可能来自 TimeKeeper。尝试在没有冻结的情况下运行,我敢打赌错误会消失。
标签: mongodb express mongoose mocha.js chai