I have this component, props are passed from parent component. Ingredients and activeIngredients are stored in the state of parent component.
export const IngredientsBox = ({
ingredients = [],
activeIngredients = [],
onAddIngredientHandler,
onRemoveIngredientHandler,
onResetIngredientsHandler
}) => {
return (
<Div>
{ingredients.map((name) => {
return (
<IngredientButton
name={name}
key={name}
isActive={activeIngredients.includes(name)}
onAddIngredientHandler={onAddIngredientHandler}
onRemoveIngredientHandler={onRemoveIngredientHandler}
/>
);
})}
<ResetButton onResetIngredientsHandler={onResetIngredientsHandler}></ResetButton>
</Div>
);
};
export const IngredientButton = ({ name, isActive, onAddIngredientHandler, onRemoveIngredientHandler }) => {
const onClick = isActive ? onRemoveIngredientHandler : onAddIngredientHandler;
return (
<Button active={isActive} onClick={() => onClick(name)}>
{name}
</Button>
);
};
What I wanna do is to test this component in isolation, but can't figure out how to imitate parent component state to change dynamically, after every method call.
import React from 'react';
import {IngredientsBox} from './IngredientsBox';
import renderer from 'react-test-renderer';
// ingredients and activeIngredients are supposed to imitate parent component state
let ingredients = ['sugar', 'honey', 'mustard', 'watermelon'];
let activeIngredients = [];
const onAddIngredientHandler = (name) => {
activeIngredients = [...activeIngredients, name]
}
const onRemoveIngredientHandler = (name) => {
activeIngredients = activeIngredients.filter((value) => value !== name)
};
test('Button toggle the class on click', () => {
const component = renderer.create(
<IngredientsBox
ingredients={ingredients}
activeIngredients = {activeIngredients}
isActive = {activeIngredients.includes(name)}
onAddIngredientHandler = {onAddIngredientHandler}
onRemoveIngredientHandler = {onRemoveIngredientHandler}
/>
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
tree.children[0].props.onClick(); // I expect this to add this element to activeIngredients and it ofcourse works.
tree = component.toJSON();
expect(tree).toMatchSnapshot();
tree.children[0].props.onClick(); // I expect this to remove this element from activeRecipes, it doesn't work, it adds it one more time, and so on. I understand this behaviour is because onClick method was assigned at the beginning and it doesn't change.
tree = component.toJSON();
expect(tree).toMatchSnapshot()
})
Is there any way to make it behave like react component with render() method? So it rerender with fresh state each time?
Aucun commentaire:
Enregistrer un commentaire