Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Importing images used the 'import' keyword for the image 'src' breaks jest test #26749

Closed
rsipakov opened this issue Jun 30, 2021 · 6 comments
Closed
Assignees
Labels
bug Issue was opened via the bug report template. please verify canary The issue should be verified against next@canary. It will be closed after 30 days of inactivity

Comments

@rsipakov
Copy link
Contributor

rsipakov commented Jun 30, 2021

What version of Next.js are you using?

11.0.1

What version of Node.js are you using?

16.3.0

What browser are you using?

Safari

What operating system are you using?

macOS

How are you deploying your application?

Vercel

Describe the Bug

Error message when simple jest test running: "Image with src "placeholder-file" must use "width" and "height" properties or "layout='fill'" property."

Expected Behavior

The jest test should pass because 'width' and 'height' for static images can be automatically defined in Next.js 11.

To Reproduce

file index.js

import vercel from '../public/vercel.svg
...
<Image
   alt="Vercel Logo"
   className={styles.logo}
   src={vercel}
   width={80}
/>
...

file fileMock.js

module.exports = 'placeholder-file'

file HomeTest.js

import Home from '../pages/index'
import { render } from '@testing-library/react'

// `describe` is not required, but it helps the tests read nicely
describe('The Home Page Component', () => {
  // Each test for the component will get an `it` block
  it('should have exactly 1 `main` section', () => {
    // The getByRole will error if there are less or more than 1 element found
    const { getByRole } = render(<Home />)
    const main = getByRole('main')

    expect(main).toBeInTheDocument()
  })
})

file jest.config.js

module.exports = {
  // Automatically clear mock calls and instances between every test
  clearMocks: true,
  // The directory where Jest should output its coverage files
  coverageDirectory: ".coverage",
  moduleNameMapper: {
    "\\.(css|less|scss|sss|styl)$": "<rootDir>/node_modules/jest-css-modules",
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
    "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
  },
  // A list of paths to modules that run some code to configure or set up the testing framework before each test
  setupFilesAfterEnv: ['./jest.setup.js'],
  testPathIgnorePatterns: [
    "<rootDir>/.next/",
    "<rootDir>/node_modules/"
  ],
  transform: {
    "^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
    // transformer for svg files
    "^.+\\.svg$": "<rootDir>/svgTransform.js"
  }
}
@rsipakov rsipakov added the bug Issue was opened via the bug report template. label Jun 30, 2021
@alexsabdev
Copy link

As a workaround, try to mock the component in jest.setup.js:

jest.mock('next/image', () => ({
  __esModule: true,
  default: () => {
    return 'Next image stub'; // whatever
  },
}));

@vx17rt
Copy link

vx17rt commented Aug 4, 2021

I feel it's kinda related to my case,
I'm getting Error: Uncaught [Error: An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received "default"] in my tests, when I statically import image like

 import logo from "public/logo.png";

and later use it

<Image src={logo} height={24} width={24} alt="logo" />

Mocking the whole 'next/image' module helps, though

@thepuzzlemaster
Copy link

thepuzzlemaster commented Oct 13, 2021

Updated my sample with a new version that actually renders an <img> element

If you'd like to create a manual mock for this (also did the same for next/head), create the following file:
__mocks__/next/image.tsx

And in it:

import * as React from 'react'
import { ImageProps } from 'next/image'

const mock = (props: ImageProps): React.ReactElement => {
  // in my case, I was only using these props, but you may need to filter out more if you are using more props
  // that shouldn't be rested onto an <img /> element 
  const { objectFit, objectPosition, src, ...filteredProps } = props

  return <img src={src.toString()} {...filteredProps} />
}

export default mock

kodiakhq bot pushed a commit that referenced this issue Oct 13, 2021
#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
natew pushed a commit to natew/next.js that referenced this issue Feb 16, 2022
vercel#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 -> vercel#26749

## Feature

- [X] Documentation added

## Documentation / Examples

- [X] Make sure the linting passes
@jankaifer jankaifer self-assigned this Dec 1, 2022
@jankaifer jankaifer added the please verify canary The issue should be verified against next@canary. It will be closed after 30 days of inactivity label Dec 1, 2022
@github-actions
Copy link
Contributor

github-actions bot commented Dec 1, 2022

Please verify that your issue can be recreated with next@canary.

Why was this issue marked with the please verify canary label?

We noticed the provided reproduction was using an older version of Next.js, instead of canary.

The canary version of Next.js ships daily and includes all features and fixes that have not been released to the stable version yet. You can think of canary as a public beta. Some issues may already be fixed in the canary version, so please verify that your issue reproduces by running npm install next@canary and test it in your project, using your reproduction steps.

If the issue does not reproduce with the canary version, then it has already been fixed and this issue can be closed.

How can I quickly verify if my issue has been fixed in canary?

The safest way is to install next@canary in your project and test it, but you can also search through closed Next.js issues for duplicates or check the Next.js releases.

My issue has been open for a long time, why do I need to verify canary now?

Next.js does not backport bug fixes to older versions of Next.js. Instead, we are trying to introduce only a minimal amount of breaking changes between major releases.

What happens if I don't verify against the canary version of Next.js?

An issue with the please verify canary that receives no meaningful activity (e.g. new comments that acknowledge verification against canary) will be automatically closed and locked after 30 days.

If your issue has not been resolved in that time and it has been closed/locked, please open a new issue, with the required reproduction, using next@canary.

I did not open this issue, but it is relevant to me, what can I do to help?

Anyone experiencing the same issue is welcome to provide a minimal reproduction following the above steps. Furthermore, you can upvote the issue using the 👍 reaction on the topmost comment (please do not comment "I have the same issue" without repro steps). Then, we can sort issues by votes to prioritize.

I think my reproduction is good enough, why aren't you looking into it quicker?

We look into every Next.js issue and constantly monitor open issues for new comments.

However, sometimes we might miss one or two due to the popularity/high traffic of the repository. We apologize, and kindly ask you to refrain from tagging core maintainers, as that will usually not result in increased priority.

Upvoting issues to show your interest will help us prioritize and address them as quickly as possible. That said, every issue is important to us, and if an issue gets closed by accident, we encourage you to open a new one linking to the old issue and we will look into it.

Useful Resources

@balazsorban44
Copy link
Member

This issue has been automatically closed because it wasn't verified against next@canary. If you think it was closed by accident, please leave a comment. If you are running into a similar issue, please open a new issue with a reproduction. Thank you.

@github-actions
Copy link
Contributor

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 10, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Issue was opened via the bug report template. please verify canary The issue should be verified against next@canary. It will be closed after 30 days of inactivity
Projects
None yet
Development

No branches or pull requests

6 participants