Test thrown errors in Next.js 14 with Storybook

Next.js Error Handling has a nice way to gracefully handle unexpected errors. But if you want to test this in Storybook (edge cases, not-so-unexpected-errors, etc), the uncaught exception will be displayed but not logged or testable in the interface.

If you're using interaction tests, using an ErrorBoundary decorator with a fallback, you can render something that can be tested.

Loading...
export default function ErrorBoundaryDecorator( Story: StoryFn, context: StoryContext ) { return ( <ErrorBoundary fallbackRender={({error}) => <div>Error: {error.toString()}</div>} > <Story /> </ErrorBoundary> ); }

In your story, include the decorator, the test.dangerouslyIgnoreUnhandledErrors prop in parameters, and you can now test for whatever you rendered in fallbackRender.

Loading...
export const WithThrownError: Story = { decorators: [ErrorBoundaryDecorator], parameters: { test: { dangerouslyIgnoreUnhandledErrors: true, }, }, play: async ({canvasElement}) => { const canvas = within(canvasElement); await expect( await canvas.findByText('Error: thrown error string') ).toBeInTheDocument(); }, };

dangerouslyIgnoreUnhandledErrors sounds less than optimal, but without setting this, the uncaught exception will cause your interaction test to fail. I would only set this where I'm using the ErrorBoundaryDecorator for more control.

Published June 16, 2024