1. jest-serializer-html
Jest snapshot serializer that beautifies HTML.
jest-serializer-html
Package: jest-serializer-html
Created by: rayrutjes
Last modified: Wed, 18 Oct 2023 14:43:39 GMT
Version: 7.1.0
License: MIT
Downloads: 2,654,759
Repository: https://github.com/rayrutjes/jest-serializer-html

Install

npm install jest-serializer-html
yarn add jest-serializer-html

A Jest snapshot serializer that beautifies HTML.

NPM version
Build Status

When using this Jest serializer, it will turn any string starting with '<' to nicely indented HTML in the snapshot.

This serializer is based on diffable-html which is an opinionated HTML formatter that will ease readability of diffs in case of failing snapshot tests.

Install

Add the package as a dev-dependency:

 # With npm
npm install --save-dev jest-serializer-html

# With yarn
yarn add --dev jest-serializer-html

Update package.json to let Jest know about the serializer:

 "jest": {
  "snapshotSerializers": ["jest-serializer-html"]
}

Vanilla JS Example

 test('should beautify HTML', () => {
  expect('<ul><li><a href="#">My HTML</a></li></ul>').toMatchSnapshot();
});

Will output:

 exports[`should beautify HTML 1`] = `
<ul>
  <li>
    <a href="#">
      My HTML
    </a>
  </li>
</ul>
`;

Vue.js component output example

 import Vue from 'vue';
const Hello = {
  props: {
    msg: {
      type: String,
      default: 'World'
    }
  },
  template: `
    <h1>Hello ${ msg }!</h1>
    <ul id="main-list" class="list"><li><a href="#">My HTML</a></li></ul>
  `
};

test('should beautify HTML', () => {
  const Component = Vue.extend(Hello);
  const vm = new Component({
    propsData: {
      msg: 'You'
    }
  });

  vm.$mount();

  expect(vm.$el.outerHTML).toMatchSnapshot();
});

Will output:

 exports[`should beautify HTML 1`] = `
<h1>
  Hello You!
</h1>
<ul id="main-list"
    class="list"
>
  <li>
    <a href="#">
      My HTML
    </a>
  </li>
</ul>
`;

You can read more about the HTML formatting here.

Special thanks

This package was inspired by the amazing post here: Jest for all: Episode 1 — Vue.js by Cristian Carlesso.

RELATED POST

10 Must-Know Windows Shortcuts That Will Save You Time

10 Must-Know Windows Shortcuts That Will Save You Time

Arrays vs Linked Lists: Which is Better for Memory Management in Data Structures?

Arrays vs Linked Lists: Which is Better for Memory Management in Data Structures?

Navigating AWS Networking: Essential Hacks for Smooth Operation

Navigating AWS Networking: Essential Hacks for Smooth Operation

Achieving Stunning Visuals with Unity's Global Illumination

Achieving Stunning Visuals with Unity's Global Illumination

Nim's Hidden Gems: Lesser-known Features for Writing Efficient Code

Nim's Hidden Gems: Lesser-known Features for Writing Efficient Code