So I was trying to learn about testing in React and I have this: Button.js
and Button.test.js
The question is commented along with the code below:
// Button.js import React from 'react'; import { string, bool, func } from 'prop-types'; import { StyledButton } from './styled' const Button = ({ size, text, }) => ( <StyledButton size={size} // the test will alway fail with result: // Expected value to be: "Join us" // Received: undefined // Unless I add add this line below text={text} > {text} // but the text props is here. That is my current practice of passing the props to the children, am I missing anything? </StyledButton> ); Button.propTypes = { size: string, text: string, }; Button.defaultProps = { size: '', text: '', }; export default Button; // Button.test.js import React from 'react'; import { shallow } from 'enzyme'; import Button from '../../components/Button/Button'; describe('Component: Button', () => { const minProps = { text: '', size: '', }; it('renders a button in size of "small" with text in it', () => { const wrapper = shallow( <Button {...minProps} size="small" text="Join us" /> ); expect(wrapper.prop('size')).toBe('small'); expect(wrapper.prop('text')).toBe('Join us'); }); }); // StyledButton import Button from 'antd/lib/button'; const StyledButton = styled(Button)` &.ant-btn { padding: 0 24px; ${({ size }) => { if (size === 'small') { return css` font-size: 14px; line-height: 32px; `; } return null; }}; `; export { StyledButton };
Does anyone know why the test will not pass unless I pass the props to the StyledButton
?
Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.
You need to find the StyledButton
in the Button
component before asserting the props
// Button.test.js import React from 'react'; import { shallow } from 'enzyme'; import Button from '../../components/Button/Button'; import { StyledButton } from './styled' describe('Component: Button', () => { const minProps = { text: '', size: '', }; it('renders a button in size of "small" with text in it', () => { const wrapper = shallow( <Button {...minProps} size="small" text="Join us" /> ); expect(wrapper.find(StyledButton).prop('size')).toBe('small'); expect(wrapper.find(StyledButton).prop('text')).toBe('Join us'); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With