Skip to content

Commit 99760f0

Browse files
mbelskyKent C. Dodds
andcommitted
feat(prettyDOM): add helpful error message (#367)
Co-authored-by: Kent C. Dodds <[email protected]>
1 parent 7f8de89 commit 99760f0

File tree

2 files changed

+48
-12
lines changed

2 files changed

+48
-12
lines changed

src/__tests__/pretty-dom.js

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,16 @@ test('prettyDOM supports truncating the output length', () => {
2626
})
2727

2828
test('prettyDOM defaults to document.body', () => {
29+
const defaultInlineSnapshot = `
30+
"<body>
31+
<div>
32+
Hello World!
33+
</div>
34+
</body>"
35+
`
2936
renderIntoDocument('<div>Hello World!</div>')
30-
expect(prettyDOM()).toMatchInlineSnapshot(`
31-
"<body>
32-
<div>
33-
Hello World!
34-
</div>
35-
</body>"
36-
`)
37+
expect(prettyDOM()).toMatchInlineSnapshot(defaultInlineSnapshot)
38+
expect(prettyDOM(null)).toMatchInlineSnapshot(defaultInlineSnapshot)
3739
})
3840

3941
test('prettyDOM supports receiving the document element', () => {
@@ -58,4 +60,22 @@ test('logDOM logs prettyDOM to the console', () => {
5860
`)
5961
})
6062

63+
describe('prettyDOM fails with first parameter without outerHTML field', () => {
64+
test('with array', () => {
65+
expect(() => prettyDOM(['outerHTML'])).toThrowErrorMatchingInlineSnapshot(
66+
`"Expected an element or document but got Array"`,
67+
)
68+
})
69+
test('with number', () => {
70+
expect(() => prettyDOM(1)).toThrowErrorMatchingInlineSnapshot(
71+
`"Expected an element or document but got number"`,
72+
)
73+
})
74+
test('with object', () => {
75+
expect(() => prettyDOM({})).toThrowErrorMatchingInlineSnapshot(
76+
`"Expected an element or document but got Object"`,
77+
)
78+
})
79+
})
80+
6181
/* eslint no-console:0 */

src/pretty-dom.js

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,34 @@ const getMaxLength = dom =>
2020

2121
const {DOMElement, DOMCollection} = prettyFormat.plugins
2222

23-
function prettyDOM(
24-
dom = getDocument().body,
25-
maxLength = getMaxLength(dom),
26-
options,
27-
) {
23+
function prettyDOM(dom, maxLength, options) {
24+
if (!dom) {
25+
dom = getDocument().body
26+
}
27+
if (typeof maxLength !== 'number') {
28+
maxLength = getMaxLength(dom)
29+
}
30+
2831
if (maxLength === 0) {
2932
return ''
3033
}
3134
if (dom.documentElement) {
3235
dom = dom.documentElement
3336
}
3437

38+
let domTypeName = typeof dom
39+
if (domTypeName === 'object') {
40+
domTypeName = dom.constructor.name
41+
} else {
42+
// To don't fall with `in` operator
43+
dom = {}
44+
}
45+
if (!('outerHTML' in dom)) {
46+
throw new TypeError(
47+
`Expected an element or document but got ${domTypeName}`,
48+
)
49+
}
50+
3551
const debugContent = prettyFormat(dom, {
3652
plugins: [DOMElement, DOMCollection],
3753
printFunctionName: false,

0 commit comments

Comments
 (0)