Skip to content

Commit

Permalink
feat(test-utils): add displayEl option
Browse files Browse the repository at this point in the history
  • Loading branch information
kentcdodds committed Apr 22, 2021
1 parent 44fdc58 commit 0267dc4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/__tests__/test-utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,15 @@ test('gives a nice error', () => {
test('can use a function a nice error', () => {
expect(() =>
alfredTip(() => expect(true).toBe(false), 'This is an extra error'),
).toThrow()
).toThrowError(/this is an extra error/i)
})

test('does nothing if shouldThrow is false', () => {
alfredTip(false, 'This is an extra error')
})

test('prints an element', () => {
expect(() =>
alfredTip(true, 'oh no', {displayEl: () => document.createElement('div')}),
).toThrowError(/oh no.*<div \/>/is)
})
7 changes: 7 additions & 0 deletions src/test-utils.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import chalk from 'chalk'
import {prettyDOM} from '@testing-library/react'

function alfredTip(
shouldThrow: unknown | (() => unknown),
tip: string | ((error: unknown) => string),
{displayEl}: {displayEl?: true | ((error: unknown) => HTMLElement)} = {},
) {
let caughtError
if (typeof shouldThrow === 'function') {
Expand All @@ -19,6 +21,11 @@ function alfredTip(
const error = new Error(chalk.red(`🚨 ${tipString}`))
// get rid of the stack to avoid the noisy codeframe
error.stack = ''
if (displayEl) {
const el =
typeof displayEl === 'function' ? displayEl(caughtError) : document.body
error.message += `\n\n${chalk.reset(prettyDOM(el))}`
}
throw error
}

Expand Down

0 comments on commit 0267dc4

Please sign in to comment.