Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Allow disabling colorized debug output #1166

Merged
merged 1 commit into from Sep 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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