I have built a React app (v16.13.1) and am testing it with Jest (v25.1.0). When I run npm test
the tests all pass fine, but when I run npm test -- --coverage
all of the components return undefined
and all of the snapshot tests fail.
It's happening with every component in the app. A typical example of a component exhibiting this behaviour is:
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();
});
});
These tests all used to pass just fine but now they are failing but only when the coverage
flag is enabled.
What am I doing wrong?
I think I've seen this before: For stateless components, you may need to define displayName prop. https://github.com/facebook/jest/issues/1824#issuecomment-250478026