用开玩笑模仿猫鼬模型

har*_*nsa 12 mongodb node.js jestjs

我试图模仿一个猫鼬模型jest,但正在收到Cannot create property 'constructor' on number '1'错误.我能够通过使用下面显示的2个文件创建项目来重现该问题.有没有办法模拟猫鼬模型jest

./model.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const schema = new Schema({
  name: String
})

module.exports = mongoose.model('Test', schema)
Run Code Online (Sandbox Code Playgroud)

./model.test.js

jest.mock('./model')
const Test = require('./model')

// Test.findOne.mockImplementation = () => {
//   ...
// }
Run Code Online (Sandbox Code Playgroud)

错误:

 FAIL  ./model.test.js
  ? Test suite failed to run

    TypeError: Cannot create property 'constructor' on number '1'

      at ModuleMockerClass._generateMock (../../jitta/sandbox/rest_api/node_modules/jest-mock/build/index.js:458:34)
      at Array.forEach (native)
      at Array.forEach (native)
      at Array.forEach (native)
Run Code Online (Sandbox Code Playgroud)

更新:

似乎是一个开玩笑的错误. https://github.com/facebook/jest/issues/3073

小智 8

好吧,我有同样的问题,所以我创作这个包来解决这个问题:https: //www.npmjs.com/package/mockingoose

这就是你如何使用它让我们说这是你的模型:

import mongoose from 'mongoose';
const { Schema } = mongoose;

const schema = Schema({
    name: String,
    email: String,
    created: { type: Date, default: Date.now }
})

export default mongoose.model('User', schema);
Run Code Online (Sandbox Code Playgroud)

这是你的考验:

it('should find', () => {
  mockingoose.User.toReturn({ name: 2 });

  return User
  .find()
  .where('name')
  .in([1])
  .then(result => {
    expect(result).toEqual({ name: 2 });
  })
});
Run Code Online (Sandbox Code Playgroud)

checkout the tests文件夹以获取更多示例:https: //github.com/alonronin/mockingoose/blob/master/ tests /index.test.js

没有连接数据库!


Ste*_*e L 8

另一种解决方案是spyOn模型prototype功能。

例如,这将使MyModel.save()失败:

    jest.spyOn(MyModel.prototype, 'save')
      .mockImplementationOnce(() => Promise.reject('fail update'))
Run Code Online (Sandbox Code Playgroud)

您可以习惯于mockImplementationOnce不必mockRestore间谍。但是您也可以使用mockImplementation和使用类似的东西:

afterEach(() => {
  jest.restoreAllMocks()
})
Run Code Online (Sandbox Code Playgroud)

已通过"mongoose": "^4.11.7"和测试"jest": "^23.6.0"