Enzyme render fails when importing image with webpack while testing with Jest

Viewed 5398

I want to test if a simple component renders (as I'm still figuring out Jest). The application itself loads an image with webpack to display the logo.

When I try to mount/render/shallow the stateless component, Jest throws an error.

 FAIL  src/components/blog/blogList.spec.jsx
  ● Test suite failed to run

    /home/requinard/Projects/manus-frontend/src/img/manus_logo.png: Unexpected character '�' (1:0)
      > 1 | �PNG
          | ^
        2 | 
        3 | 
        4 | IHDR��G}    pHYs.#.#x�?vtEXtSoftwareAdobe ImageReadyq�e<K�IDATx��]  \�����=)DY

It seems it's trying to load the image and failing at that. How can I stop Jest from loading the image for any component, or make it load the image so that it'll still render.

Stateless component:

import React from 'react';
PropTypes from 'prop-types';
import { BlogPostHeader } from './blogPostHeader';
import './blog.scss';

export const BlogList = props => (
  <div className="blog-list">
    {props.posts.map((post, key) => <BlogPostHeader post={post} key={key} className="blog-list-item" />)}
  </div>
);

BlogList.propTypes = {
  posts: PropTypes.array,
};

The test for the stateless component

import React from 'react';
import { render } from 'enzyme';
import { BlogList } from './BlogList';


describe('<BlogList >', () => {
  it('should render in enzyme', () => {
    const wrapper = render(<BlogList />);
    expect(wrapper).toBeTruthy();
  });
});

The component rendering the image (simplified):

import logo from '../img/logo.png';'
  <div className="logo-container"><img src={logo} className="logo-child" /> </div>
4 Answers

Adding some more details to what @Samyn mentioned. You need to have this entry in your package.json

  "jest": {
    "modulePaths": [
      "__mocks__"
    ],
    "moduleNameMapper":  {
      "\\.(css|sass|scss)$": "styleMock.js",
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "fileMock.js"
    },
    "testPathIgnorePatterns": [
      "/node_modules/",
      "/build/"
    ]
  }

you need to have the mocks folder mentioned in the config, in the same folder as this package.json. Create the styleMock.js and fileMock.js files inside them.

/* styleMock.js contents */
module.exports = {}

/* fileMock.js contents */
module.exports = 'test-file-stub';

In case you are using create-react-app and changed scripts section in package.json to include enzyme (that's how started to get the same error and I got to this question), you don't need to do that, create-react-app already includes jest and enzyme, see https://github.com/facebook/create-react-app/issues/2564

Related