Skip to content

Commit

Permalink
feat: Allow disabling colorized debug output (#1166)
Browse files Browse the repository at this point in the history
  • Loading branch information
MynockSpit committed Sep 17, 2022
1 parent 2a9ee25 commit c9b197c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
14 changes: 14 additions & 0 deletions src/__tests__/pretty-dom.js
Expand Up @@ -152,3 +152,17 @@ test('prettyDOM can include all elements with a custom filter', () => {
</body>
`)
})

test('prettyDOM supports a COLORS environment variable', () => {
const {container} = render('<div>Hello World!</div>')

const noColors = prettyDOM(container, undefined, {highlight: false})
const withColors = prettyDOM(container, undefined, {highlight: true})

// process.env.COLORS is a string, so make sure we test it as such
process.env.COLORS = 'false'
expect(prettyDOM(container)).toEqual(noColors)

process.env.COLORS = 'true'
expect(prettyDOM(container)).toEqual(withColors)
})
27 changes: 22 additions & 5 deletions src/pretty-dom.js
Expand Up @@ -4,10 +4,27 @@ import {getUserCodeFrame} from './get-user-code-frame'
import {getDocument} from './helpers'
import {getConfig} from './config'

const inNode = () =>
typeof process !== 'undefined' &&
process.versions !== undefined &&
process.versions.node !== undefined
const shouldHighlight = () => {
let colors
try {
colors = JSON.parse(process?.env?.COLORS)
} catch (e) {
// If this throws, process?.env?.COLORS wasn't parsable. Since we only
// care about `true` or `false`, we can safely ignore the error.
}

if (typeof colors === 'boolean') {
// If `colors` is set explicitly (both `true` and `false`), use that value.
return colors
} else {
// If `colors` is not set, colorize if we're in node.
return (
typeof process !== 'undefined' &&
process.versions !== undefined &&
process.versions.node !== undefined
)
}
}

const {DOMCollection} = prettyFormat.plugins

Expand Down Expand Up @@ -61,7 +78,7 @@ function prettyDOM(dom, maxLength, options = {}) {
const debugContent = prettyFormat.format(dom, {
plugins: [createDOMElementFilter(filterNode), DOMCollection],
printFunctionName: false,
highlight: inNode(),
highlight: shouldHighlight(),
...prettyFormatOptions,
})
return maxLength !== undefined && dom.outerHTML.length > maxLength
Expand Down

0 comments on commit c9b197c

Please sign in to comment.