我已经构建了一个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