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

feat(next/jest): mock static imports of svg, image and others differently #36907

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions packages/next/build/jest/__mocks__/fileMock.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,2 @@
module.exports = {
src: '/img.jpg',
height: 24,
width: 24,
blurDataURL: 'data:image/png;base64,imagedata',
}
// as jest suggested in https://jestjs.io/docs/webpack#handling-static-assets
module.exports = 'test-file-stub'
7 changes: 7 additions & 0 deletions packages/next/build/jest/__mocks__/imageMock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// mock StaticImageData interface
module.exports = {
src: '/mock-image.png',
height: 24,
width: 24,
blurDataURL: 'data:image/png;base64,imagedata',
}
11 changes: 11 additions & 0 deletions packages/next/build/jest/__mocks__/svgMock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const React = require('react')

// mock @svgr/webpack
module.exports = (...props) => {
const svg = React.createElement('svg', {
fill: 'none',
xmlns: 'http://www.w3.org/2000/svg',
...props[0],
})
return svg
}
12 changes: 8 additions & 4 deletions packages/next/build/jest/jest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,13 +92,17 @@ export default function nextJest(options: { dir?: string } = {}) {
// Handle CSS imports (without CSS modules)
'^.+\\.(css|sass|scss)$': require.resolve('./__mocks__/styleMock.js'),

// Handle image imports
// Handle image imports as a StaticImageData-typed png image
'^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp)$': require.resolve(
`./__mocks__/fileMock.js`
`./__mocks__/imageMock.js`
),

// Keep .svg to it's own rule to make overriding easy
'^.+\\.(svg)$': require.resolve(`./__mocks__/fileMock.js`),
// Handle svg imports as @svgr/webpack plugin handles
'^.+\\.(svg)$': require.resolve(`./__mocks__/svgMock.js`),

// Handle other files as jest suggested
'^.+\\.(eot|otf|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
require.resolve(`./__mocks__/fileMock.js`),

// custom config comes last to ensure the above rules are matched,
// fixes the case where @pages/(.*) -> src/pages/$! doesn't break
Expand Down