lee.david.cs

Mocking next/image in Storybook

February 23, 2021

As of the date I am writing this, Storybook will break on any component that renders an Image component from next/image.

That kind of sucks, but that's alright. We can stub out the implementation of next/image with a mock in the meantime.

Example stub implementation for next/image

1// file: ./mocks/next/image.js
2
3// Stub implementation of next/image. May need to be adapted depending on how you use next/image
4
5import { createElement } from "react";
6
7const Image = ({
8 children,
9 className,
10 objectFit,
11 objectPosition,
12 src,
13 style,
14 ...restProps
15}) => {
16 return createElement(
17 "img",
18 {
19 className,
20 src,
21 style: {
22 ...style,
23 objectFit,
24 objectPosition
25 },
26 ...restProps
27 },
28 children
29 );
30};
31
32export default Image;

/ Example webpack config for storybook, using the next/image mock /

1// .storybook/main.js
2
3const path = require("path");
4const webpack = require("webpack");
5
6module.exports = {
7 /* ... */
8 webpackFinal: (config) => {
9 /**
10 * !HACK
11 * @description next/image doesn't work with storybook, so we are stubbing it with a mock
12 * @author David Lee
13 * @date February 23, 2021
14 */
15 config.plugins.push(
16 new webpack.NormalModuleReplacementPlugin(
17 /^next\/image$/,
18 path.resolve(__dirname, "./mocks/next/image.js")
19 )
20 );
21
22 return config;
23 }
24};

Now, you can generate snapshots, visually test, make demos, etc. of your components that make use of next/image!

Happy coding! -- David Lee