与Chai和Mocha一起对猫鼬模型进行单元测试



我正在尝试使用Mocha和Chai在Nodejs应用程序上运行单元测试。我正在使用Mongodb和Mongoose框架。这是我的学生.model.js

var mongoose = require('mongoose')
var studentsSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: {
type: String,
required: true
},
email: String,
phone: Number,
address: String,
username: String,
password: String
});

var Students = mongoose.model('Student', studentsSchema);

module.exports = Students;

这是我的学生.model.test.js

let assert = require('chai').assert;
var expect = require('chai').expect;
var mongoose = require('mongoose');
var Students = require('../models/students.model');
describe ('Student',function(){
before(function (done) {
mongoose.connect('mongodb://localhost/mongoose_basics');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', function() {
console.log('We are connected to test database!');
done();
});
});
it('student works!',function(){
var s = new Students({name:'krishna'});
s.save(err => {
if(err) { return done(); }
throw new Error('Should generate error!');
});
});
after(function(done){
mongoose.connection.db.dropDatabase(function(){
mongoose.connection.close(done);
});
});
});

我想用Mocha和Chai运行单元测试。当我运行mocha student.model.test.js时,我得到以下错误

TypeError: Students is not a constructor

我不知道为什么它返回的不是构造函数。

这是require语句的问题,它只导入与您的模型相关的函数,所以如果您想获得模型,请尝试以下语句:

var Students = require('../models/students.model').Students;

最新更新