猫鼬保存方法用笑话测试假通过

Mongoose save method test false pass with jest

我尝试用 Jest 测试 Mongoose 模型。该模型包含一个名为 email 的 属性,它必须包含唯一值。这是我尝试进行的测试 运行:

import { expect } from 'chai'
import mongoose from 'mongoose'
import bluebird from 'bluebird'

import Author from '../Author' // this is the model I try to test

mongoose.Promise = bluebird
describe('email key', () => {
  beforeAll((done) => {
    mongoose.connect('mongodb://127.0.0.1:27017/test')

    let db = mongoose.connection

    db.on('error', (err) => {
      done.fail(err)
    })

    db.once('open', () => {
      done()
    })
  })

  test('duplicate email', () => {
    const a = new Author({
      email: 'email@gmail.com',
      name: 'some',
      nickname: 'oether',
      role: 'admin'
    })

    const b = new Author({
      email: 'email@gmail.com',
      name: 'a',
      nickname: 'a',
      role: 'admin'
    })

    a.save()
      .then((doc) => console.log(doc))
      .catch((err) => console.log(err))

    b.save() // should throw error on test
      .then((doc) => console.log(doc))
      .catch((err) => console.log(err))
  })

  afterAll((done) => {
    mongoose.connection.db.dropDatabase().then(() => {
      mongoose.connection.close()
      done()
    })
  })
})

这是架构文件:

import mongoose from 'mongoose'
const authorSchema = new mongoose.Schema({
  email: {
    type: String,
    unique: true,
    index: true
  }
})

const authorModel = mongoose.model('Author', authorSchema)
export default authorModel

我期待什么?

我希望在 b 上执行 save() 方法时在控制台中出现错误,类似于 email field should contain unique values

我能得到什么?

控制台显示测试成功通过(✓ duplicate email (2ms))。此外,测试正在被挂起并且不会终止 util 我按 ctrl+c 手动终止它。

a.save 和 b.save 正在同时执行。我不确定为什么测试挂起,但尝试:

a.save()
 .then.(() => b.save())
 .then(console.log) 
 .catch(console.log)