用Jest测试时如何模拟父组件状态

时间:2019-10-21 10:48:02

标签: javascript reactjs testing jestjs

我有这个组件,道具从父组件传递。成分和activeIngredients以父组件的状态存储。

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>
  );
};

我想做的是孤立地测试此组件,但无法弄清楚如何在每次方法调用之后模仿父组件状态以动态更改。

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()

})

是否有任何方法可以使其表现与render()方法的react组件一样?所以每次都以新状态重新渲染?

0 个答案:

没有答案