reactjs - 启用 --coverage 标志时 React Jest 快照测试失败
问题描述
我已经构建了一个 React 应用程序 (v16.13.1) 并正在使用 Jest (v25.1.0) 对其进行测试。当我运行npm test
测试时,所有测试都通过了,但是当我运行npm test -- --coverage
所有组件时,所有组件都返回undefined
并且所有快照测试都失败了。
应用程序中的每个组件都会发生这种情况。表现出此行为的组件的典型示例是:
src/components/Card.js
import React from 'react';
import PropTypes from 'prop-types';
const Card = ({ title, subtitle, children }) => (
<div className="card">
{title && <div className="card-header">{title}</div>}
<div className="card-body">
{subtitle && <div className="small mb-3">{subtitle}</div>}
<div className="mt-3">{children}</div>
</div>
</div>
);
Card.propTypes = {
title: PropTypes.string,
subtitle: PropTypes.string,
children: PropTypes.node.isRequired
};
Card.defaultProps = {
title: null,
subtitle: null
};
export default Card;
src/components/Card.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import Card from './Card';
let tree;
describe('without title or subtitle', () => {
beforeAll(() => {
tree = renderer.create(
<Card>
<p>Hello there</p>
</Card>
);
});
it('renders correctly', () => {
expect(tree).toMatchSnapshot();
});
});
describe('with title and subtitle', () => {
beforeAll(() => {
tree = renderer.create(
<Card title="Test" subtitle="This is a test">
<p>Hello there</p>
</Card>
);
});
it('renders correctly', () => {
expect(tree).toMatchSnapshot();
});
});
这些测试过去都可以通过,但现在它们失败了,但只有在coverage
启用标志时才会失败。
我究竟做错了什么?
解决方案
我想我以前见过这个:对于无状态组件,您可能需要定义 displayName 属性。 https://github.com/facebook/jest/issues/1824#issuecomment-250478026
推荐阅读
- amazon-web-services - How to map fields automatically in appflow?
- r - 如何在 R 中绘制多个 rgb 图像
- python - Python GUI using Kivy. Cannot save figures when running .exe file
- reactjs - How To Create Dynamic Input box with label and Render Input value in ReactJs
- reactjs - How to build pre-render pages based on environments
- python - Getting a database dump from a remote server without an intermediary file
- c# - How to print an image with a thermal printer
- javascript - AngularJS - get relative coordinates to the container object, within SVG on mouse click WITH HOVER STYLE
- electron - Uncaught ReferenceError: Cannot access 'dialog' before initialization
- macos - how can i reset my mac terminal to write a command?