简体   繁体   中英

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

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>

For mocking images and other static assets, they actually have an item in the wiki.

https://facebook.github.io/jest/docs/webpack.html

I did not note that <rootDir> gets replaced by Jest itself, and you HAVE to include it yourself.

So with a file structure of

config \
  jest \
    fileMock.js
    styleMock.js
src |
package.json

I have to include the following lines in package.json

"moduleNameMapper": {
      "\\.(css|scss|less)$": "<rootDir>/config/jest/styleMock.js",
      "\\.(png|jpg|gif|ttf|eot|svg)$": "<rootDir>/config/jest/fileMock.js"
    }

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'; 

If the image is required, you can mock it, like:

import mockery from "mockery";

mockery.enable();
mockery.registerMock('../img/logo.png', 0)

Find more info here https://www.npmjs.com/package/mockery

如果您正在使用package.json中的create-react-app和更改脚本部分来包含酶(这就是如何开始获得相同的错误并且我得到了这个问题),您不需要这样做,创建 - 反应-app已经包含了jest和酶,请参阅https://github.com/facebook/create-react-app/issues/2564

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM