Skip to content

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

Closed

Description

@rsipakov

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"
  }
}

Activity

  1. added
    bugIssue was opened via the bug report template.
    on Jun 30, 2021
  2. alexsabdev commented on Jul 23, 2021

    @alexsabdev

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

    jest.mock('next/image', () => ({
      __esModule: true,
      default: () => {
        return 'Next image stub'; // whatever
      },
    }));
    
  3. vx17rt commented on Aug 4, 2021

    @vx17rt

    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

  4. thepuzzlemaster commented on Oct 13, 2021

    @thepuzzlemaster

    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
    
  5. self-assigned this
    on Dec 1, 2022
  6. github-actions commented on Dec 1, 2022

    @github-actions
    Contributor

    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

  7. balazsorban44 commented on Jan 10, 2023

    @balazsorban44
    Contributor

    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.

  8. github-actions commented on Feb 10, 2023

    @github-actions
    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.

  9. locked as resolved and limited conversation to collaborators on Feb 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugIssue was opened via the bug report template.please verify canaryPlease verify the issue with the latest canary branch.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions