Unverified Commit 541259d9 authored by Angelo P's avatar Angelo P Committed by GitHub

Update testing based on Failed to parse src "test-file-stub" on `next… (#29039)

…/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 
<Image
              height='91'
              width='198'
              layout='fixed'
              src={quizImage}
              alt='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(<Home />); // 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
```
<!--
Thanks for opening a PR! Your contribution is much appreciated.
In order to make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below.
Choose the right checklist for the change that you're making:
-->

## Bug

possibly related to -> #26749

## Feature

- [X] Documentation added

## Documentation / Examples

- [X] Make sure the linting passes
parent eed43115
...@@ -319,6 +319,14 @@ These files aren't useful in tests but importing them may cause errors, so we wi ...@@ -319,6 +319,14 @@ These files aren't useful in tests but importing them may cause errors, so we wi
module.exports = {}; 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). 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** **Extend Jest with custom matchers**
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment