Skip to content

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

@rsipakov

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

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