vendredi 30 octobre 2020

How to make Enzyme or Jest wait until context work

I am passing a function to the context that is called when the component that receives this context is mounted.This function set value to parent component state.

Example is here https://codesandbox.io/s/react-jest-enzyme-forked-16s74?file=/src/App.js

In browser this work like that - first time state is {validation: {}}, and then it update to {validate: {name: 'some-name'}}.

But in test it's work only first time, and state doesn't update to {validate: {name: 'some-name'}}.

How can i fix this ?

Components
Validation

export class Validation extends React.Component {
  static childContextTypes = {
    addValidation: PropTypes.func
  };

  state = {
    validations: {}
  };

  getChildContext() {
    return {
      addValidation: (name, value) => {
        this.setState((prevState) => ({
          ...prevState,
          validations: { ...prevState.validations, [name]: value }
        }));
      }
    };
  }

  render() {
    console.log(this.state);
    return this.props.children;
  }
}

ValidationField

export class ValidationField extends React.Component {
  static contextTypes = {
    addValidation: PropTypes.func
  };

  componentDidMount() {
    const { name, validation } = this.props;
    this.context.addValidation && this.context.addValidation(name, validation);
  }

  render() {
    return <input />;
  }
}

Test

it("", () => {
    const wrapper = mount(
      <Validation>
        <ValidationField name="fieldName" validation="blabla" />
      </Validation>
    );

    expect(wrapper.state()).toBe({
      validations: {
        fieldName: "blabla"
      }
    });
  });   

Aucun commentaire:

Enregistrer un commentaire