2

I have a simple express routine to save incoming data:

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

And I want to write unit test for this by using mockingoose and supertest.

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);
});

And I get this error:

  ● 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

I couldn't figure out how to fix this. Any suggestion?

Murat Çorlu
  • 8,207
  • 5
  • 53
  • 78

1 Answers1

1

I didn't give full code example here because of trying to keep question simple. But it turned out this problem doesn't occur with a situation that simple. And I realised that problem occurs about some external plugins(mongoose-slug-hero here) because they are using more methods of Mongoose models that mockingoose doesn't provide. Problem can be different on all different plugins. Also populate doesn't work properly with mockingoose too. You need to do some more workaround for fixing it.

At the end I run away from mockingoose and started using jest-mongodb involuntarily(Because I think this is anti pattern for unit-tests).

Murat Çorlu
  • 8,207
  • 5
  • 53
  • 78