Enzyme processing fails when importing image with webpack when testing with Jest
I want to test what a simple component looks like (since I'm still good with Jest). The app itself loads the image using webpack to display the logo.
When I try to install / display / smaller 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 to be trying to load the image and it fails. How can I stop Jest from loading the image for any component, or force it to load the image so that it shows up anyway.
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,
};
Test for a 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();
});
});
Component displaying an image (simplified):
import logo from '../img/logo.png';'
<div className="logo-container"><img src={logo} className="logo-child" /> </div>
source to share
For mock images and other static assets, they have an item on the wiki.
https://facebook.github.io/jest/docs/webpack.html
I didn't notice that it <rootDir>
is being replaced by Jest itself and you have to enable it yourself.
So with the file structure
config \
jest \
fileMock.js
styleMock.js
src |
package.json
I need 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"
}
source to share
If an image is required you can mock it, for example:
import mockery from "mockery";
mockery.enable();
mockery.registerMock('../img/logo.png', 0)
Find more information here https://www.npmjs.com/package/mockery
source to share