Skip to content

Instantly share code, notes, and snippets.

@wtho
Last active March 28, 2019 11:23
Show Gist options
  • Select an option

  • Save wtho/6be94c1b4537d50d437dd30bb5637dae to your computer and use it in GitHub Desktop.

Select an option

Save wtho/6be94c1b4537d50d437dd30bb5637dae to your computer and use it in GitHub Desktop.
DOM element rendering without Angular's class ids

Quick Install

  • npm install --save-dev --save-exact pretty-format@24.0.0
  • copy DOMElementNoClassIdSnapshotSerializer.js to your project folder
  • add './DOMElementNoClassIdSnapshotSerializer.js' to snapshotSerializers in your jest config

Problem

Angular does create HTML for components like this:

<h1 class="ng-tns-c1-0">
  app works! 
  <app-inner-comp class="ng-tns-c1-0" />
  <span class="ng-tns-c1-0">
    Some Text
  </span>
</h1>

The ID in the class (c1-0) iterates with each component.

If you use snapshots in jest, the ids change depending on the number of tests you run in a test suite.

No Class ID Serializer

This serializer removes all ids in classes after ng-tsn- and replaces them with x. This way seralized components stay consistent and independent of test number/order.

Example:

<h1 class="ng-tns-cx-x">
  app works! 
  <app-inner-comp class="ng-tns-cx-x" />
  <span class="ng-tns-cx-x">
    Some Text
  </span>
</h1>

Dependencies

This serializer is copied from the DOMElement.js-Serializer from the package pretty-format which is located in the repository github.com/facebook/jest.

Some adjustments were made to handle the rendering of the class attribute.

To not copy everything, this serializer heavily depends on pretty-format v24.0.0. If you want to use it, please add "pretty-format": "24.0.0" (exact vesrion, no semver range) to your project. The serializer depends on internals of pretty-format and therefore I do not know if another version than 24.0.0 is supported.

/**
* Original Work
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* Modified work
* Copyright (c) 2019 Thomas Wirth
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
const {
printChildren,
printComment,
printElement,
printElementAsLeaf,
printProps,
printText,
} = require('pretty-format/build/plugins/lib/markup');
const ELEMENT_NODE = 1;
const TEXT_NODE = 3;
const COMMENT_NODE = 8;
const FRAGMENT_NODE = 11;
const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/;
const testNode = (nodeType, name) =>
(nodeType === ELEMENT_NODE && ELEMENT_REGEXP.test(name)) ||
(nodeType === TEXT_NODE && name === 'Text') ||
(nodeType === COMMENT_NODE && name === 'Comment') ||
(nodeType === FRAGMENT_NODE && name === 'DocumentFragment');
const test = (val) =>
val &&
val.constructor &&
val.constructor.name &&
testNode(val.nodeType, val.constructor.name);
function getClassIdCleanedValue(attribute) {
if (!attribute.name === 'class') {
return attribute.value;
}
const classes = attribute.value.split(' ');
const cleanedClasses = classes.map(cssClass => {
if (!cssClass.startsWith('ng-tns')) {
return cssClass;
}
return cssClass.replace(/\d+/g, 'x');
})
return cleanedClasses.join(' ');
}
function nodeIsText(node) {
return node.nodeType === TEXT_NODE;
}
function nodeIsComment(node) {
return node.nodeType === COMMENT_NODE;
}
function nodeIsFragment(node) {
return node.nodeType === FRAGMENT_NODE;
}
const serialize = (
node,
config,
indentation,
depth,
refs,
printer,
) => {
if (nodeIsText(node)) {
return printText(node.data, config);
}
if (nodeIsComment(node)) {
return printComment(node.data, config);
}
const type = nodeIsFragment(node)
? `DocumentFragment`
: node.tagName.toLowerCase();
if (++depth > config.maxDepth) {
return printElementAsLeaf(type, config);
}
return printElement(
type,
printProps(
nodeIsFragment(node)
? []
: Array.from(node.attributes)
.map(attr => attr.name)
.sort(),
nodeIsFragment(node)
? []
: Array.from(node.attributes).reduce(
(props, attribute) => {
props[attribute.name] = getClassIdCleanedValue(attribute);
return props;
},
{},
),
config,
indentation + config.indent,
depth,
refs,
printer,
),
printChildren(
Array.prototype.slice.call(node.childNodes || node.children),
config,
indentation + config.indent,
depth,
refs,
printer,
),
config,
indentation,
);
};
module.exports = {
serialize, test
}
module.exports = {
snapshotSerializers: [
'./DOMElementNoClassIdSnapshotSerializer.js',
],
};
MIT License
Original Work
For Jest software
Copyright (c) 2014-present, Facebook, Inc. and its affiliates. All Rights Reserved
Modified Work
Copyright (c) 2019 Thomas Wirth
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment