DEV Community

Cover image for How to compare mongoose model objects in jest while excluding _id
Adrian Matei for Codever

Posted on • Originally published at codever.dev

1

How to compare mongoose model objects in jest while excluding _id

The schema model object in Mongoose provides an _id that is of type ObjectId. If you are not interested in comparing value of this attribute when you compare it compare objects in jest, you can exclude it by calling the toObject method of the mongoose model and set the _id object to nothing via the spread operator, something similar to the following:

expect({...resultBookmark.toObject(), _id: {}}).toEqual({...expectedBookmark.toObject(), _id: {}})
Enter fullscreen mode Exit fullscreen mode

The complete testing method with the setup is shown in the snippet bellow,
where expected bookmark model should match the mapped bookmark from the given request:

const showdown = require('showdown');
const Bookmark = require('../../model/bookmark');
const bookmarkRequestMapper = require('./bookmark-request.mapper');

jest.mock('showdown', () => {
  const makeHtml = jest.fn(() => '<p>This is a test bookmark</p>');
  return {
    Converter: jest.fn().mockImplementation(() => ({makeHtml})),
  };
});

describe('toBookmark', () => {
  const req = {
    body: {
      _id: '123',
      name: 'Test Bookmark',
      location: 'https://example.com',
      language: 'en',
      description: 'This is a test bookmark',
      tags: ['test'],
      public: true,
    },
    params: {
      userId: '456',
    },
  };

  beforeEach(() => {
    showdown.Converter.mockClear();
    showdown.Converter().makeHtml.mockClear();
    req.body.descriptionHtml = undefined;
    req.body.youtubeVideoId = undefined;
    req.body.stackoverflowQuestionId = undefined;
  });

  it('should use descriptionHtml if it is provided', () => {
    req.body.descriptionHtml = '<p>This is a test bookmark</p>';

    const expectedBookmark = new Bookmark({
      _id: '123',
      name: 'Test Bookmark',
      location: 'https://example.com',
      language: 'en',
      description: 'This is a test bookmark',
      descriptionHtml: '<p>This is a test bookmark</p>',
      tags: ['test'],
      public: true,
      userId: '456',
      likeCount: 0,
      youtubeVideoId: null,
      stackoverflowQuestionId: null,
    });

    const resultBookmark = bookmarkRequestMapper.toBookmark(req);

    expect({...resultBookmark.toObject(), _id: {}}).toEqual({...expectedBookmark.toObject(), _id: {}})
    expect(showdown.Converter().makeHtml).not.toHaveBeenCalled();
  });
});
Enter fullscreen mode Exit fullscreen mode

Project: codever - File: bookmark-request.mapper.test.js


Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.

Codever is open source on Github⭐🙏

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay