Skip to content

Update styleSheetSerializer with defensive check for null/undefined nodes #450

@shoosya

Description

@shoosya

Problem Description

Snapshot tests fail due to unguarded recursion when jest-style-components encounters a null or undefined child node.

PrettyFormatPluginError: Cannot read properties of undefined (reading 'children')
 ❯ getNodes ../node_modules/@cx/serializer/lib/styleSheetSerializer.js:10:12
 ❯ ../node_modules/@cx/serializer/lib/styleSheetSerializer.js:11:50
 ❯ getNodes ../node_modules/@cx/serializer/lib/styleSheetSerializer.js:11:31
 ❯ Object.serialize ../node_modules/@cx/serializer/lib/styleSheetSerializer.js:136:19
 ❯ printPlugin ../node_modules/@vitest/snapshot/node_modules/@vitest/pretty-format/dist/index.js:995:44
 ❯ format ../node_modules/@vitest/snapshot/node_modules/@vitest/pretty-format/dist/index.js:1146:16

Solution

  • Add defensive guards for cases when node is null/undefined.
  • Prevent snapshots from failing when node is not an iterable.

const getNodes = (node, nodes = []) => {

const getNodes = (node, nodes = []) => {
  if (!node || typeof node !== 'object') {
    return nodes;
  }

  nodes.push(node);

  if (node.children && typeof node.children === 'object') {
    try {
      Array.from(node.children).forEach((child) => getNodes(child, nodes));
    } catch (_) {
    }
  }

  return nodes;
};

Pull request: #451

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions