Introduction
Jest is a test library from facebook. We won't have to install it if the project is a CRA project (creat-react-app).
This article is to note an easy test for React components.
React component
import React from 'react'
import PropTypes from 'prop-types'
const FooterItem = ({externalLink, imageSrc, imageAltText}) => {
return (
<span className="btn-o">
<a href={externalLink}>
<img src={imageSrc} alt={imageAltText}/>
</a>
</span>
)
}
FooterItem.propTypes = {
imageSrc: PropTypes.string.isRequired,
imageAltText: PropTypes.string.isRequired,
externalLink: PropTypes.string.isRequired
}
export default FooterItem
Screenshot match test
- Create a test component (FooterItem.test.js) in the test folder
import React from 'react'
import FooterItem from '../components/FooterItem';
import twitter from '../images/twitter.png';
import renderer from 'react-test-renderer';
describe('<FooterItem/>', () => {
test('Snapshot', () => {
const component = renderer.create(<FooterItem imageSrc={twitter} imageAltText="twitter"
externalLink="https://twitter.com/JenHsuanHsieh"/>);
let snapshot = component.toJSON();
expect(snapshot).toMatchSnapshot();
});
});
2.Run the test
- Type the following command in the terminal
npm test
It will generate the snapshots folder.
It will store screenshot files. When we run test second time and Jest will compare screen shots to make sure they are the same.
Coverage
- Type the following command in the terminal
npm test -- --coverage
- Check the content from the terminal
Articles
There are some of my articles. Feel free to check if you like!
- My blog-posts for software developing: https://medium.com/a-layman
- My web resume: https://jenhsuan.github.io/ALayman/cover.html
- Facebook page: https://www.facebook.com/imalayman
Top comments (0)