我想测试一个简单的组件是否渲染(因为我还在搞清楚Jest).应用程序本身使用webpack加载图像以显示徽标.
当我尝试挂载/渲染/浅化无状态组件时,Jest会抛出错误.
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
它似乎正试图加载图像而失败了.如何阻止Jest加载任何组件的图像,或者让它加载图像以便它仍然可以渲染.
无状态组件:
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,
};
对无状态组件的测试
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();
});
});
渲染图像的组件(简化):
import logo from '../img/logo.png';'
<div className="logo-container"><img src={logo} className="logo-child" /> </div>
解决方法:
对于模拟图像和其他静态资产,它们实际上在wiki中有一个项目.
https://facebook.github.io/jest/docs/webpack.html
我没有注意到< rootDir>被Jest取代,你必须自己包含它.
所以用文件结构
config \
jest \
fileMock.js
styleMock.js
src |
package.json
我必须在package.json中包含以下行
"moduleNameMapper": {
"\\.(css|scss|less)$": "<rootDir>/config/jest/styleMock.js",
"\\.(png|jpg|gif|ttf|eot|svg)$": "<rootDir>/config/jest/fileMock.js"
}