最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Enzyme render fails when importing image with webpack while testing with Jest - Stack Overflow

programmeradmin0浏览0评论

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>

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>
Share Improve this question asked May 19, 2017 at 10:22 requinardrequinard 9611 gold badge12 silver badges24 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 14

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

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

发布评论

评论列表(0)

  1. 暂无评论