From 541259d9922801027b4de29515c86a7dcbb790e1 Mon Sep 17 00:00:00 2001 From: Angelo P Date: Wed, 13 Oct 2021 11:13:24 -0400 Subject: [PATCH] =?UTF-8?q?Update=20testing=20based=20on=20Failed=20to=20p?= =?UTF-8?q?arse=20src=20"test-file-stub"=20on=20`next=E2=80=A6=20(#29039)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit …/image` Error While learning how to test next.js applications I came across this error when testing components using next/image with an image import eg: ``` // /quiz-hero import Image from 'next/image'; import quizImage from '../../public/undraw-quiz.svg'; // In render QuizImage ``` ### Error -> Failed to parse src "test-file-stub" on `next/image`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://) This is fixed by adding a "/" to the beginning of your file-stub module export string. This is not an error when you're awaiting an image using async waitFor, But comes up as an error when you're testing a component that holds another component with a "next/image" import. eg: ``` // quizHero.test.tsx works like this without change. const image = await waitFor(() => screen.findByAltText('QuizImage')); // but index.test.tsx fails rendering the homepage without the change. render(); // Error: Failed to parse src "test-file-stub" on `next/image`... // with change to __mocks__/fileMock quizHero.test.tsx //test pass index.test.tsx //test pass ``` ## Bug possibly related to -> #26749 ## Feature - [X] Documentation added ## Documentation / Examples - [X] Make sure the linting passes --- docs/testing.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/testing.md b/docs/testing.md index 9eb373744e4b1..c90e168aa16e7 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -319,6 +319,14 @@ These files aren't useful in tests but importing them may cause errors, so we wi module.exports = {}; ``` +If you're running into the issue `"Failed to parse src "test-file-stub" on 'next/image'"`, add a '/' to your fileMock. + +```json +// __mocks__/fileMock.js + +(module.exports = "/test-file-stub") +``` + For more information on handling static assets, please refer to the [Jest Docs](https://jestjs.io/docs/webpack#handling-static-assets). **Extend Jest with custom matchers**