From 0267dc475cf8483de4509d04c013f79772d31246 Mon Sep 17 00:00:00 2001 From: "Kent C. Dodds" Date: Thu, 22 Apr 2021 15:24:35 -0600 Subject: [PATCH] feat(test-utils): add displayEl option --- src/__tests__/test-utils.tsx | 8 +++++++- src/test-utils.tsx | 7 +++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/__tests__/test-utils.tsx b/src/__tests__/test-utils.tsx index 139a343..aa87e79 100644 --- a/src/__tests__/test-utils.tsx +++ b/src/__tests__/test-utils.tsx @@ -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.*
/is) +}) diff --git a/src/test-utils.tsx b/src/test-utils.tsx index bd4bbae..44553c1 100644 --- a/src/test-utils.tsx +++ b/src/test-utils.tsx @@ -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') { @@ -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 }