嘲笑猫鼬模型 [英] Mocking Mongoose model with jest

查看:49
本文介绍了嘲笑猫鼬模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 jest 模仿猫鼬模型,但是却得到无法在数字'1'错误上创建属性'constructor'.通过使用下面显示的2个文件创建项目,我能够重现该问题.有没有一种方法可以用 jest 模拟猫鼬模型?

I am trying to mock a mongoose model with jest, but is getting Cannot create property 'constructor' on number '1' error. I was able to reproduce the issue by creating the project with 2 files shown below. Is there a way to mock a mongoose model with jest?

./model.js

./model.js

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

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

module.exports = mongoose.model('Test', schema)

./model.test.js

./model.test.js

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

// Test.findOne.mockImplementation = () => {
//   ...
// }

错误:

 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)

更新:

似乎是在开玩笑. https://github.com/facebook/jest/issues/3073

推荐答案

另一种解决方案是 spyOn 模型 prototype 函数.

An other solution is to spyOn the model prototype functions.

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

    jest.spyOn(MyModel.prototype, 'save')
      .mockImplementationOnce(() => Promise.reject('fail update'))

您可以使用 mockImplementationOnce 来不必对间谍进行 mockRestore .但是您也可以使用 mockImplementation 并使用类似的内容:

You can use mockImplementationOnce to not having to mockRestore the spy. But you can also use mockImplementation and use something like :

afterEach(() => {
  jest.restoreAllMocks()
})

经过"mongoose":"^ 4.11.7" "jest":"^ 23.6.0" 的测试.

这篇关于嘲笑猫鼬模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆