【问题标题】:Mockingoose _id: Cannot read property 'where' of undefined errorMockingoose _id:无法读取未定义错误的属性“位置”
【发布时间】:2020-08-25 19:25:06
【问题描述】:

我有一个简单的快速例程来保存传入的数据:

app.post('/news', async (req, res, next) => {
  const news = await model.create(req.body);
  res.status(201).json(news);
});

我想为此使用mockingoosesupertest 编写单元测试。

it('should create news', async () => {
  mockingoose(NesModel).toReturn({ _id: '507f191e810c19729de860ea', title: 'dadsd' }, 'save');

  const res = await request(app)
    .post('/news')
    .send({
      title: 'ABC',
      content: 'adbasdasdsad'
    });

  expect(res.statusCode).toBe(201);
});

我得到这个错误:

  ● News › should create news

    ValidationError: News validation failed: _id: Cannot read property 'where' of undefined

      at new ValidationError (node_modules/mongoose/lib/error/validation.js:31:11)
      at model.Document.invalidate (node_modules/mongoose/lib/document.js:2563:32)
      at node_modules/mongoose/lib/document.js:2385:17
      at node_modules/mongoose/lib/schematype.js:1181:9

我不知道如何解决这个问题。有什么建议吗?

【问题讨论】:

  • 我有一个非常相似的问题,但根本没有使用 mockingoose。只需使用 Mongoose...

标签: node.js unit-testing express mongoose mockingoose


【解决方案1】:

我没有在这里给出完整的代码示例,因为我试图让问题保持简单。但事实证明,这个问题不会发生在这么简单的情况下。我意识到一些外部插件(这里是mongoose-slug-hero)会出现问题,因为它们使用了更多的Mongoose模型方法,而Mockingoose没有提供。所有不同插件的问题都可能不同。 populate 也不能与 mockingoose 一起正常工作。你需要做some more workaround 来修复它。

最后我逃离了 mockingoose 并开始不自觉地使用jest-mongodb(因为我认为这是单元测试的反模式)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-14
    • 2020-09-03
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 2013-09-03
    • 2023-03-17
    相关资源
    最近更新 更多