Node.js 开玩笑地模仿猫鼬验证器

Node.js 开玩笑地模仿猫鼬验证器,node.js,mongodb,unit-testing,mongoose,jestjs,Node.js,Mongodb,Unit Testing,Mongoose,Jestjs,我正在测试mongoose模型的验证,在尝试模拟验证程序时,该模型仍然具有对原始函数的引用,因此验证会继续调用原始函数 我想测试是否调用了验证器函数get,但是由于验证器转到db,我需要模拟它 这是我的模型: const { hasRequiredCustoms } = require('../utils/validators') const ProductSchema = new Schema({ customs: { type: [String], validate:

我正在测试mongoose模型的验证,在尝试模拟验证程序时,该模型仍然具有对原始函数的引用,因此验证会继续调用原始函数

我想测试是否调用了验证器函数get,但是由于验证器转到db,我需要模拟它

这是我的模型:

const { hasRequiredCustoms } = require('../utils/validators')

const ProductSchema = new Schema({
  customs: {
    type: [String],
    validate: hasRequiredCustoms // <- This is the validator
  }
})

const Product = mongoose.model('Product', ProductSchema)

module.exports = Product
这是验证程序的模拟:

module.exports = {
  hasRequiredCustoms(val) {
    console.log('Original')
    // validation logic
    return result
  },
  //etc...
}
const validators = jest.genMockFromModule('../validators')

function hasRequiredCustoms (val) {
  console.log('Mock')
  return true
}

validators.hasRequiredCustoms = hasRequiredCustoms

module.exports = validators
以及测试:

test('Should be invalid if required customs missing: price', done => {
  jest.mock('../../utils/validators')

  function callback(err) {
    if (!err) done()
  }

  const m = new Product( validProduct )
  m.validate(callback)
})
每次运行测试时,控制台都会记录原始测试。为什么引用仍然返回到原始模块?似乎我缺少了一些关于require如何工作或mongoose存储验证器引用的超级基本概念

谢谢你的帮助