diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f6c31fb0d4a..8db6c9c6ebbc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -64,6 +64,7 @@ - `[jest-worker]` Handle `ERR_IPC_CHANNEL_CLOSED` errors properly ([#11143](https://github.com/facebook/jest/pull/11143)) - `[pretty-format]` [**BREAKING**] Convert to ES Modules ([#10515](https://github.com/facebook/jest/pull/10515)) - `[pretty-format]` Only call `hasAttribute` if it's a function ([#11000](https://github.com/facebook/jest/pull/11000)) +- `[pretty-format]` Handle jsdom attributes properly ([#11189](https://github.com/facebook/jest/pull/11189)) ### Chore & Maintenance diff --git a/packages/pretty-format/src/__tests__/DOMElement.test.ts b/packages/pretty-format/src/__tests__/DOMElement.test.ts index 8c86488ebf0e..6a39f2576512 100644 --- a/packages/pretty-format/src/__tests__/DOMElement.test.ts +++ b/packages/pretty-format/src/__tests__/DOMElement.test.ts @@ -582,4 +582,9 @@ Testing.`; ].join('\n'), ); }); + + it('handles jsdom attributes properly', () => { + const attributes = require('jsdom/lib/jsdom/living/attributes'); + expect(DOMElement.test(attributes)).toBe(false); + }); }); diff --git a/packages/pretty-format/src/plugins/DOMElement.ts b/packages/pretty-format/src/plugins/DOMElement.ts index e500620dd5d0..0b2e81653d3a 100644 --- a/packages/pretty-format/src/plugins/DOMElement.ts +++ b/packages/pretty-format/src/plugins/DOMElement.ts @@ -22,12 +22,20 @@ const FRAGMENT_NODE = 11; const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/; +const testHasAttribute = (val: any) => { + try { + return typeof val.hasAttribute === 'function' && val.hasAttribute('is'); + } catch { + return false; + } +}; + const testNode = (val: any) => { const constructorName = val.constructor.name; const {nodeType, tagName} = val; const isCustomElement = (typeof tagName === 'string' && tagName.includes('-')) || - (typeof val.hasAttribute === 'function' && val.hasAttribute('is')); + testHasAttribute(val); return ( (nodeType === ELEMENT_NODE &&