【问题标题】:Unit testing mongoose model with Chai and Mocha使用 Chai 和 Mocha 对猫鼬模型进行单元测试
【发布时间】:2018-12-30 02:55:55
【问题描述】:

我正在尝试使用 Mocha 和 Chai 在我的 Nodejs 应用程序上运行单元测试。我正在将 Mongodb 与 Mongoose 框架一起使用。这是我的 student.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;

这是我的 student.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

我不确定为什么它返回的不是构造函数。

【问题讨论】:

  • 您是唯一可以检查您的情况下Students 是什么的人。从上面的代码中,我希望它是构造函数。我看到的唯一问题是它应该是var studentsSchema = new mongoose.Schema(...),而不是var studentsSchema = mongoose.Schema(...),但我不确定它是如何导致问题的。
  • 根据 mongoose 文档,它应该是 var studentsSchema = mongoose.Schema(...) 而不是 var studentsSchema = new mongoose.Schema(...) 没有新的 mongoosejs.com/docs
  • 这似乎是文档中唯一没有new 使用它的地方。它是一个构造函数。无论如何,它不太可能导致您遇到的错误。

标签: node.js mongoose mocha.js tdd chai


【解决方案1】:

问题在于 require 语句只导入与您的模型相关的函数,因此如果您想获取模型,请尝试以下语句:

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

【讨论】:

    猜你喜欢
    • 2019-05-04
    • 2021-09-14
    • 2018-01-02
    • 2017-08-11
    • 1970-01-01
    • 2014-11-25
    • 2021-09-27
    • 2017-02-18
    • 2015-05-16
    相关资源
    最近更新 更多