使用Jest测试Mongoose模型

时间:2018-02-27 21:36:14

标签: javascript mongoose jest

我正试图用Jest测试我的Mongoose模型。我的模型看起来像这样:

const mongoose = require('mongoose');
const slug = require('slugs');
mongoose.Promise = global.Promise;

const cinemaSchema = new mongoose.Schema({
  name: {
    type: String,
    trim: true,
    required: 'Please enter a cinema name'
  },
  slug: String,
  description: {
    type: String,
    trim: true
  },
  capacity: {
    type: Number,
    required: 'Please enter a capacity'
  }
});

cinemaSchema.pre('save', function(next) {
  if (!this.isModified('name')) {
    next();
    return
  }
  this.slug = slug(this.name);
  next();
})

module.exports = mongoose.model('Cinema', cinemaSchema)

我在下面写了一些测试,但是当我尝试运行它们并访问它们的结果时,我收到了undefined。我在这里使用.validate功能,因为我不想真正点击我的数据库。

测试看起来像这样。我已经删除了期望,因为我只是想访问错误:

const mongoose = require('mongoose');
const Cinema = require('./Cinema');

describe('Cinema', () => {
  it('Should return an error if a number is passed as the name', (done) => {
    const cinema = new Cinema({name: 2, description: 'good', capacity: 1});
    cinema.validate(response => {
      console.log(response);
      done();
    });

  })
})

知道为什么我在这里定义不明确吗?

1 个答案:

答案 0 :(得分:3)

因为mongoose会尝试将电影院name投射到字符串,并且它成功地做到了。请尝试将capacity更改为字符串:capacity: 'saasd' 你会得到类似的东西:

{
  ValidationError: Cinema validation failed: capacity: Cast to Number failed for value "saasd" at path "capacity"
        at ValidationError.Object.<anonymous>.ValidationError.inspect (/Users/fabio/playground/mongoose/node_modules/mongoose/lib/error/validation.js:56:24)
        at formatValue (util.js:430:38)
        at inspect (util.js:324:10)
        at format (util.js:191:12)
        at CustomConsole.log (/Users/fabio/playground/mongoose/node_modules/jest-util/build/Console.js:135:53)
        at cinema.validate.response (/Users/fabio/playground/mongoose/cinema.test.js:12:15)
        at /Users/fabio/playground/mongoose/node_modules/mongoose/lib/document.js:1432:5
        at /Users/fabio/playground/mongoose/node_modules/mongoose/lib/document.js:1564:9
        at /Users/fabio/playground/mongoose/node_modules/kareem/index.js:135:16
        at _combinedTickCallback (internal/process/next_tick.js:131:7)
        at process._tickCallback (internal/process/next_tick.js:180:9)
   errors: {
     capacity: MongooseError {
       message: 'Cast to Number failed for value "saasd" at path "capacity"',
       name: 'CastError',
       stringValue: '"saasd"',
       kind: 'Number',
       value: 'saasd',
       path: 'capacity',
       reason: [Object]
     }
   },
   _message: 'Cinema validation failed',
   name: 'ValidationError'
}