Pre-study
Importing images used the 'import' keyword for the image 'src' breaks jest test #26749
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.]
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 ;
},
}));
To check what is rendered
For example,
const renderResult = render();
container = renderResult.container;
console.debug(container.innerHTML);
This will output the following in the terminal:
Mocked Nav