DEV Community

Cover image for One easy way to set the name in jest repetitive tests (test.each)
Adrian Matei for Codever

Posted on • Originally published at codever.dev

1

One easy way to set the name in jest repetitive tests (test.each)

One easy way to display a custom name for each test.each test in jest, is to place the text name in the first element of each array of the input table for the method and use it as name in the test.each method - ('%s', (testname, req, expectedBookmark), as in the following snippet:

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

  test.each([
    [
      'should return a new bookmark',
      req,
      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,
      })
    ],
    [
      'should set youtubeVideoId if it is provided',
      {...req,
        body : {
        ...req.body,
          youtubeVideoId: 'abcd1234'
        }
      },
      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: 'abcd1234',
        stackoverflowQuestionId: null,
      })
    ],
    [
      'should set stackoverflowQuestionId if it is provided',
      {...req,
        body : {
        ...req.body,
          stackoverflowQuestionId: 123456
        }
      },
      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: 123456,
      })
    ],
  ])('%s', (testname, req, expectedBookmark) => {
    const resultBookmark = bookmarkRequestMapper.toBookmark(req);

    expect({...resultBookmark.toObject(), _id: {}}).toEqual({...expectedBookmark.toObject(), _id: {}});
    expect(showdown.Converter).toHaveBeenCalledTimes(1);
    expect(showdown.Converter().makeHtml).toHaveBeenCalledTimes(1);
    expect(showdown.Converter().makeHtml).toHaveBeenCalledWith('This is a test bookmark');
  });
});
Enter fullscreen mode Exit fullscreen mode

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

Of course you are free to display other data where appropiate...


Reference -

https://jestjs.io/docs/api#testeachtablename-fn-timeout

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

Codever is open source on Github⭐🙏

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay