I'm making a Counter component (called 'Servings'). The servings amount and methods to increment and decrement come as props from parent components:
const Servings: React.FC<ServingsProps> = ({
servings,
onDecrease,
onIncrease,
className,
}) => {
return (
<div className={'servings-conuter ' + className}>
<span className='servings-conuter__label'>servings</span>
<button
className='servings-conuter__button'
onClick={onDecrease}
aria-label='decrease servings'
data-test='decrease-servings'
>
-
</button>
<span
className='servings-conuter__count'
data-test='servings-label'
>
{servings}
</span>
<button
className='servings-conuter__button'
onClick={onIncrease}
aria-label='increase servings'
data-test='increase-servings'
>
+
</button>
</div>
)
}
then in my test file when I invoke the onDecrement method for exmaple (which I'm mocking), the servings props doesn't get updated:
const defaultProps = {
servings: 3,
onDecrease: jest.fn(),
onIncrease: jest.fn(),
className: 'test'
}
const setup = (props = {}) => {
const setupProps = { ...defaultProps, ...props }
return mount(<Servings {...setupProps} />)
}
describe('Servings component', () => {
it('renders with no errors', () => {
const wrapper = setup()
expect(wrapper.exists()).toBe(true)
})
it('decrease servings correclty', () => {
const wrapper = setup()
wrapper
.find('button[data-test=\'decrease-servings\']')
.simulate('click')
//wrapper.props().onDecrease() // heard this is better then simulate, cause it will be soon deprecated, is it true?
//wrapper.update() // is this actually needed? doesnt seem to make a difference
const servingsLabel = wrapper.find('span[data-test=\'servings-label\']').text()
expect(defaultProps.onDecrease).toBeCalled(); // this passes, so the function does get called
expect(servingsLabel).toBe('2')
})
})
and indeed the test doesn't pass: