Skip to content

Commit

Permalink
Update testing based on Failed to parse src "test-file-stub" on `next… (
Browse files Browse the repository at this point in the history
#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
  • Loading branch information
angelopoole authored Oct 13, 2021
1 parent eed4311 commit 541259d
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
Expand Down

0 comments on commit 541259d

Please sign in to comment.