DEV Community

Jen C.
Jen C.

Posted on

Jest - Mocking Next.js Image to handle dynamic properties in tests

Pre-study

Next.js - Image Component

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

Jest - Manual Mocks

React Testing Library

MDN JavaScript - Rest parameters

Background

When testing a React component with Jest and the React Testing Library, this error occurs if the component renders a Next.js Image component and the Next.js Image component is not mocked.

Error: Uncaught [Error: Image with src "test-file-stub" is missing required "width" property.]
Enter fullscreen mode Exit fullscreen mode

Solution

To allow passing dynamic properties into the mock image component so that it can handle different test cases, modify the mock image to accept an indefinite number of arguments as an array.

In jest/setup.js, add the following:

jest.mock('next/image', () => ({
  __esModule: true,
  default: (props) => {
    return <img {...props} />;
  },
}));
Enter fullscreen mode Exit fullscreen mode

To check what is rendered

For example,

const renderResult = render(<Header {...props} />);
container = renderResult.container;
console.debug(container.innerHTML);
Enter fullscreen mode Exit fullscreen mode

This will output the following in the terminal:

<header class="main-header"><div class="container-h"><div class="main-header__top"><a class="main-header__logo-link" href="/"><img class="main-header__logo" src="test-file-stub" alt="test alt"></a><div class="main-header__top-right"><div class="main-header__dropdown-btns"></div></div></div><div class="main-header__bottom"><nav role="navigation">Mocked Nav</nav></div></div></header>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)