Unverified Commit 6aa3dbd2 authored by Rishi's avatar Rishi Committed by GitHub

Fix: Image component ignores images.qualities in Jest environment (#89536)

- Fixes #89492
- Fixes #18415 

## Problem

When testing Next.js <Image /> components with Jest, custom
images.qualities configured in next.config.js are ignored, causing:
- Image URLs to use default quality (q=75) instead of configured values
- Warning: "Image with src ... is using quality X which is not
configured in images.qualities [75]"

### Root Cause

In production and development, Next.js uses webpack's DefinePlugin to
inject the image configuration via process.env.__NEXT_IMAGE_OPTS.
However, *Jest tests don't use webpack*, so
process.env.__NEXT_IMAGE_OPTS is undefined, causing the Image component
to fall back to default configuration.

## Solution

This PR implements a two-part fix:

1. *Jest globals population* (packages/next/src/build/jest/jest.ts):
   - Expose nextConfig.images via Jest globals.__NEXT_IMAGE_OPTS

2. *Runtime fallback* (image components):
- When process.env.__NEXT_IMAGE_OPTS is undefined, fall back to
globalThis.__NEXT_IMAGE_OPTS
   - Applied to:
     - packages/next/src/client/image-component.tsx
     - packages/next/src/shared/lib/image-external.tsx  
     - packages/next/src/client/legacy/image.tsx

## Changes

- ✅ Minimal, targeted fix (4 files, ~40 lines)
- ✅ No production/development behavior changes
- ✅ No test-only conditionals or environment checks
- ✅ Comprehensive test coverage added

## Testing

Added test in test/production/app-dir/image-jest-qualities/ that:
- Configures custom qualities [90, 100] in next.config.js
- Renders <Image quality={100} /> in Jest with jsdom
- Asserts generated image URLs contain q=100 not q=75

Test correctly *fails on canary* (shows warning about unconfigured
quality) and *passes with fix*.

## Verification

- ✅ New test passes with fix
- ✅ Existing image tests unaffected
- ✅ Addresses original issue reproduction exactly

---------
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent 610fdb8e
...@@ -103,9 +103,34 @@ export default function nextJest(options: { dir?: string } = {}) { ...@@ -103,9 +103,34 @@ export default function nextJest(options: { dir?: string } = {}) {
await lockfilePatchPromise.cur await lockfilePatchPromise.cur
} }
const imageConfig = nextConfig?.images
? {
deviceSizes: nextConfig.images.deviceSizes,
imageSizes: nextConfig.images.imageSizes,
qualities: nextConfig.images.qualities,
path: nextConfig.images.path,
loader: nextConfig.images.loader,
dangerouslyAllowSVG: nextConfig.images.dangerouslyAllowSVG,
unoptimized: nextConfig.images.unoptimized,
}
: undefined
const transpiled = (nextConfig?.transpilePackages ?? []) const transpiled = (nextConfig?.transpilePackages ?? [])
.concat(DEFAULT_TRANSPILED_PACKAGES) .concat(DEFAULT_TRANSPILED_PACKAGES)
.concat(
imageConfig
? [
// Dist paths for normal package resolution.
'next/dist/client',
'next/dist/shared/lib',
// Source paths can appear under pnpm file: installs.
'next/src/client',
'next/src/shared/lib',
]
: []
)
.join('|') .join('|')
const transpiledPathRegex = transpiled.replace(/\//g, '[\\\\/]')
const jestTransformerConfig: JestTransformerConfig = { const jestTransformerConfig: JestTransformerConfig = {
modularizeImports: nextConfig?.modularizeImports, modularizeImports: nextConfig?.modularizeImports,
...@@ -116,7 +141,9 @@ export default function nextJest(options: { dir?: string } = {}) { ...@@ -116,7 +141,9 @@ export default function nextJest(options: { dir?: string } = {}) {
serverComponents, serverComponents,
isEsmProject, isEsmProject,
pagesDir, pagesDir,
imageConfig,
} }
return { return {
...resolvedJestConfig, ...resolvedJestConfig,
...@@ -174,10 +201,13 @@ export default function nextJest(options: { dir?: string } = {}) { ...@@ -174,10 +201,13 @@ export default function nextJest(options: { dir?: string } = {}) {
...(transpiled ...(transpiled
? [ ? [
`/node_modules/(?!.pnpm)(?!(${transpiled})/)`, `/node_modules/(?!.pnpm)(?!(${transpiled})/)`,
`/node_modules/.pnpm/(?!(${transpiled.replace( // For pnpm: standard packages use "next@version", but file: refs
// use "file+..+next-repo-...". Don't ignore when the path leads
// to a transpiled package (e.g. .../node_modules/next/).
`/node_modules[\\\\/]\\.pnpm[\\\\/](?!(${transpiled.replace(
/\//g, /\//g,
'\\+' '\\+'
)})@)`, )})@)(?!.*node_modules[\\\\/](${transpiledPathRegex})[\\\\/])`,
] ]
: ['/node_modules/']), : ['/node_modules/']),
// CSS modules are mocked so they don't need to be transformed // CSS modules are mocked so they don't need to be transformed
......
...@@ -48,6 +48,7 @@ export interface JestTransformerConfig extends TransformerConfig { ...@@ -48,6 +48,7 @@ export interface JestTransformerConfig extends TransformerConfig {
modularizeImports?: NextConfig['modularizeImports'] modularizeImports?: NextConfig['modularizeImports']
swcPlugins: ExperimentalConfig['swcPlugins'] swcPlugins: ExperimentalConfig['swcPlugins']
compilerOptions: NextConfig['compiler'] compilerOptions: NextConfig['compiler']
imageConfig?: Partial<NextConfig['images']>
} }
// Jest use the `vm` [Module API](https://nodejs.org/api/vm.html#vm_class_vm_module) for ESM. // Jest use the `vm` [Module API](https://nodejs.org/api/vm.html#vm_class_vm_module) for ESM.
...@@ -96,6 +97,7 @@ const createTransformer: TransformerCreator< ...@@ -96,6 +97,7 @@ const createTransformer: TransformerCreator<
modularizeImports: inputOptions?.modularizeImports, modularizeImports: inputOptions?.modularizeImports,
swcPlugins: inputOptions?.swcPlugins, swcPlugins: inputOptions?.swcPlugins,
compilerOptions: inputOptions?.compilerOptions, compilerOptions: inputOptions?.compilerOptions,
imageConfig: inputOptions?.imageConfig,
serverReferenceHashSalt: '', serverReferenceHashSalt: '',
esm: esm:
isSupportEsm && isSupportEsm &&
......
...@@ -159,7 +159,7 @@ function getBaseSWCOptions({ ...@@ -159,7 +159,7 @@ function getBaseSWCOptions({
optimizer: { optimizer: {
simplify: false, simplify: false,
globals: jest globals: jest
? null ? undefined
: { : {
typeofs: { typeofs: {
window: globalWindow ? 'object' : 'undefined', window: globalWindow ? 'object' : 'undefined',
...@@ -313,6 +313,7 @@ export function getJestSWCOptions({ ...@@ -313,6 +313,7 @@ export function getJestSWCOptions({
jsConfig, jsConfig,
resolvedBaseUrl, resolvedBaseUrl,
pagesDir, pagesDir,
imageConfig,
serverReferenceHashSalt, serverReferenceHashSalt,
}: { }: {
isServer: boolean isServer: boolean
...@@ -325,6 +326,7 @@ export function getJestSWCOptions({ ...@@ -325,6 +326,7 @@ export function getJestSWCOptions({
resolvedBaseUrl?: ResolvedBaseUrl resolvedBaseUrl?: ResolvedBaseUrl
pagesDir?: string pagesDir?: string
serverComponents?: boolean serverComponents?: boolean
imageConfig?: Partial<NextConfig['images']>
serverReferenceHashSalt: string serverReferenceHashSalt: string
}) { }) {
let baseOptions = getBaseSWCOptions({ let baseOptions = getBaseSWCOptions({
...@@ -347,6 +349,19 @@ export function getJestSWCOptions({ ...@@ -347,6 +349,19 @@ export function getJestSWCOptions({
serverReferenceHashSalt, serverReferenceHashSalt,
}) })
// In production, webpack DefinePlugin replaces process.env.__NEXT_IMAGE_OPTS
// with an object literal at compile time. Emulate that here by enabling
// SWC's optimizer globals.envs so the same compile-time replacement happens
// during Jest transforms.
if (imageConfig) {
baseOptions.jsc.transform.optimizer.globals = {
envs: {
...baseOptions.jsc.transform.optimizer.globals?.envs,
__NEXT_IMAGE_OPTS: JSON.stringify(imageConfig),
},
} as any
}
const useCjsModules = shouldOutputCommonJs(filename) const useCjsModules = shouldOutputCommonJs(filename)
return { return {
...baseOptions, ...baseOptions,
......
export default function Page() {
return (
<main>
<h1>Image Jest Qualities Test</h1>
<p>Testing custom image qualities in Jest environment</p>
</main>
)
}
const nextJest = require('next/jest')
const createJestConfig = nextJest({
dir: './',
})
const customJestConfig = {
testEnvironment: 'jest-environment-jsdom',
}
module.exports = createJestConfig(customJestConfig)
module.exports = {
images: {
qualities: [90, 100],
},
}
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import path from 'path'
import execa from 'execa'
const appDir = path.join(__dirname, 'app')
describe('next/jest image qualities config', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
skipStart: true,
files: {
'next.config.js': `
module.exports = {
images: {
qualities: [90, 100],
},
}
`,
app: new FileRef(path.join(appDir, 'app')),
'jest.config.js': `
const nextJest = require('next/jest')
const createJestConfig = nextJest({
dir: './',
})
const customJestConfig = {
testEnvironment: 'jsdom',
}
module.exports = createJestConfig(customJestConfig)
`,
[`tests/image.test.tsx`]: `
import Image from 'next/image'
import { render, screen } from '@testing-library/react'
describe('Image quality config', () => {
it('respects custom qualities from next.config.js', () => {
render(
<Image
src="/test.jpg"
alt="test"
width={500}
height={500}
quality={100}
/>
)
const img = screen.getByRole('img')
// Should use quality=100 from our config, not default q=75
expect(img.getAttribute('src')).toContain('q=100')
expect(img.getAttribute('src')).not.toContain('q=75')
})
it('uses custom qualities for srcset generation', () => {
render(
<Image
src="/test.jpg"
alt="test"
width={500}
height={500}
sizes="100vw"
/>
)
const img = screen.getByRole('img')
// Should generate srcset with our custom qualities [90, 100]
// and not include default quality 75
const srcSet = img.getAttribute('srcset') || ''
const srcSetEntries = srcSet.split(',')
const hasCustomQualities = srcSetEntries.some(entry =>
entry.includes('q=90') || entry.includes('q=100')
)
const hasDefaultQuality = srcSetEntries.some(entry =>
entry.includes('q=75')
)
expect(hasCustomQualities).toBe(true)
expect(hasDefaultQuality).toBe(false)
})
})
`,
},
dependencies: {
jest: '29.7.0',
'jest-environment-jsdom': '29.7.0',
'@testing-library/react': '15.0.2',
'@testing-library/jest-dom': '5.17.0',
},
})
})
afterAll(() => next.destroy())
it('should pass jest tests with custom image qualities', async () => {
const result = await execa(
'pnpm',
['jest', 'tests/image.test.tsx', '--forceExit', '--verbose'],
{
cwd: next.testDir,
reject: false,
}
)
const output = result.stdout || result.stderr || ''
console.log('Jest output:', output)
expect(output).toContain('PASS')
expect(output).toMatch(/2 passed/)
})
})
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