mercredi 4 décembre 2019

Testing if button changes state, or if component appears (React)

I have a component with a button and a form. When button is visible, the form is hidden and the opposite - when we click button it dissapears and form is shown. I would like to test it either with enzyme or testing-library, but all my tests fail.

import React, { useState } from 'react';
import Form from './Form';

const FormComponent = () => {
  const [isFormVisible, setFormVisibility] = useState(false);

  function toggleFormVisibility() {
    setFormVisibility(!isFormVisible);
  }
  return (
    <section>
      {!isFormVisible && (
        <button
          id='toggle-form-button'
          data-testid='toggle-form-button'
          onClick={toggleFormVisibility}
        >
          Show form
        </button>
      )}
    {isFormVisible && <Form onCancel={toggleFormVisibility} />}
    </section>
  );
};

export default FormComponent;

My test:

describe('Form component', () => {
  it('should fire toggle form action on button click', () => {
    const setState = jest.fn();
    const useStateSpy = jest.spyOn(React, 'useState');
    useStateSpy.mockImplementation(() => [undefined, setState]);

    const component = render(
      <Form />
    );
    const showFormButton = component.getByTestId('toggle-form-button');
    Simulate.click(showFormButton);
    expect(showFormButton).toBeCalled();
  });
});

and another one:

  it('should fire toggle form action on button click', () => {
    const toggleFormVisibility = jest.fn();

    const component = render(
      <Form />
    );
    const showFormButton = component.getByTestId('toggle-form-button');
    Simulate.click(showFormButton);
    expect(toggleFormVisibility).toBeCalled();
  });

Aucun commentaire:

Enregistrer un commentaire