From eaee425a939e1a9e62575b5b51da6c2e2336481a Mon Sep 17 00:00:00 2001 From: Maxim Belsky Date: Sat, 5 Oct 2019 13:54:38 +0300 Subject: [PATCH] Explicitly check outerHTML field in dom --- src/__tests__/pretty-dom.js | 34 +++++++++++++++++++++++++++------- src/pretty-dom.js | 26 +++++++++++++++++++++----- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/src/__tests__/pretty-dom.js b/src/__tests__/pretty-dom.js index 1aa4ae83..22cf95aa 100644 --- a/src/__tests__/pretty-dom.js +++ b/src/__tests__/pretty-dom.js @@ -26,14 +26,16 @@ test('prettyDOM supports truncating the output length', () => { }) test('prettyDOM defaults to document.body', () => { + const defaultInlineSnapshot = ` + " +
+ Hello World! +
+ " +` renderIntoDocument('
Hello World!
') - expect(prettyDOM()).toMatchInlineSnapshot(` - " -
- Hello World! -
- " - `) + expect(prettyDOM()).toMatchInlineSnapshot(defaultInlineSnapshot) + expect(prettyDOM(null)).toMatchInlineSnapshot(defaultInlineSnapshot) }) test('prettyDOM supports receiving the document element', () => { @@ -58,4 +60,22 @@ test('logDOM logs prettyDOM to the console', () => { `) }) +describe('prettyDOM fails with first parameter without outerHTML field', () => { + test('with array', () => { + expect(() => prettyDOM(['outerHTML'])).toThrowErrorMatchingInlineSnapshot( + `"Expected an element or document but got Array"`, + ) + }) + test('with number', () => { + expect(() => prettyDOM(1)).toThrowErrorMatchingInlineSnapshot( + `"Expected an element or document but got number"`, + ) + }) + test('with object', () => { + expect(() => prettyDOM({})).toThrowErrorMatchingInlineSnapshot( + `"Expected an element or document but got Object"`, + ) + }) +}) + /* eslint no-console:0 */ diff --git a/src/pretty-dom.js b/src/pretty-dom.js index 28f2cfca..9f065c03 100644 --- a/src/pretty-dom.js +++ b/src/pretty-dom.js @@ -20,11 +20,14 @@ const getMaxLength = dom => const {DOMElement, DOMCollection} = prettyFormat.plugins -function prettyDOM( - dom = getDocument().body, - maxLength = getMaxLength(dom), - options, -) { +function prettyDOM(dom, maxLength, options) { + if (!dom) { + dom = getDocument().body + } + if (typeof maxLength !== 'number') { + maxLength = getMaxLength(dom) + } + if (maxLength === 0) { return '' } @@ -32,6 +35,19 @@ function prettyDOM( dom = dom.documentElement } + let domTypeName = typeof dom + if (domTypeName === 'object') { + domTypeName = dom.constructor.name + } else { + // To don't fall with `in` operator + dom = {} + } + if (!('outerHTML' in dom)) { + throw new TypeError( + `Expected an element or document but got ${domTypeName}`, + ) + } + const debugContent = prettyFormat(dom, { plugins: [DOMElement, DOMCollection], printFunctionName: false,