如何在不包括_id的同时比较开玩笑中的Mongoose模型对象
#javascript #测试 #mongodb #jest

Mongoose中的模型对象提供了一个类型ObjectId_id。如果您对比较此属性的值比较时不感兴趣,则可以通过调用Mongoose模型的toObject方法来将其比较对象,并通过传播操作员将_id对象设置为Nothing,类似于以下内容:

expect({...resultBookmark.toObject(), _id: {}}).toEqual({...expectedBookmark.toObject(), _id: {}})

用设置的完整测试方法显示在摘要中,
预期的书签模型应与给定请求相匹配映射的书签:

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

项目koude4- 文件bookmark-request.mapper.test.js


Codever的â2。使用ðcopy to mine功能将其添加到您的个人片段集合中。

codever Githubâð

的开源