Skip to content

Commit c9b197c

Browse files
authored
feat: Allow disabling colorized debug output (#1166)
1 parent 2a9ee25 commit c9b197c

File tree

2 files changed

+36
-5
lines changed

2 files changed

+36
-5
lines changed

Diff for: src/__tests__/pretty-dom.js

+14
Original file line numberDiff line numberDiff line change
@@ -152,3 +152,17 @@ test('prettyDOM can include all elements with a custom filter', () => {
152152
</body>
153153
`)
154154
})
155+
156+
test('prettyDOM supports a COLORS environment variable', () => {
157+
const {container} = render('<div>Hello World!</div>')
158+
159+
const noColors = prettyDOM(container, undefined, {highlight: false})
160+
const withColors = prettyDOM(container, undefined, {highlight: true})
161+
162+
// process.env.COLORS is a string, so make sure we test it as such
163+
process.env.COLORS = 'false'
164+
expect(prettyDOM(container)).toEqual(noColors)
165+
166+
process.env.COLORS = 'true'
167+
expect(prettyDOM(container)).toEqual(withColors)
168+
})

Diff for: src/pretty-dom.js

+22-5
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,27 @@ import {getUserCodeFrame} from './get-user-code-frame'
44
import {getDocument} from './helpers'
55
import {getConfig} from './config'
66

7-
const inNode = () =>
8-
typeof process !== 'undefined' &&
9-
process.versions !== undefined &&
10-
process.versions.node !== undefined
7+
const shouldHighlight = () => {
8+
let colors
9+
try {
10+
colors = JSON.parse(process?.env?.COLORS)
11+
} catch (e) {
12+
// If this throws, process?.env?.COLORS wasn't parsable. Since we only
13+
// care about `true` or `false`, we can safely ignore the error.
14+
}
15+
16+
if (typeof colors === 'boolean') {
17+
// If `colors` is set explicitly (both `true` and `false`), use that value.
18+
return colors
19+
} else {
20+
// If `colors` is not set, colorize if we're in node.
21+
return (
22+
typeof process !== 'undefined' &&
23+
process.versions !== undefined &&
24+
process.versions.node !== undefined
25+
)
26+
}
27+
}
1128

1229
const {DOMCollection} = prettyFormat.plugins
1330

@@ -61,7 +78,7 @@ function prettyDOM(dom, maxLength, options = {}) {
6178
const debugContent = prettyFormat.format(dom, {
6279
plugins: [createDOMElementFilter(filterNode), DOMCollection],
6380
printFunctionName: false,
64-
highlight: inNode(),
81+
highlight: shouldHighlight(),
6582
...prettyFormatOptions,
6683
})
6784
return maxLength !== undefined && dom.outerHTML.length > maxLength

0 commit comments

Comments
 (0)