测试按钮是否更改状态,或是否出现组件(反应)

时间:2019-12-04 08:52:48

标签: reactjs testing jestjs enzyme react-testing-library

我有一个带有按钮和表格的组件。当按钮可见时,表单被隐藏,而相反-当我们单击按钮时,它消失并显示表单。我想使用酶或测试库对其进行测试,但是我所有的测试均失败。

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;

我的测试:

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

和另一个:

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

2 个答案:

答案 0 :(得分:0)

在您的测试中,您似乎正在尝试渲染<Form>而不是<FormComponent>,这可能会导致测试出现问题。

在第二个测试中,也没有使用组件设置toggleFormVisibility模拟函数,因此根本不会调用该函数,上面的答案很合理,您可能需要考虑给一枪,不确定为什么要投票。

答案 1 :(得分:-1)

testing-library可以使此测试更容易:

import { render, fireEvent } from '@testing-library/react'

const { isFormVisible, setFormVisibility } = render(<Form />);
fireEvent.click(getByText('Show form'));
expect(getByRole('button')).toHaveAttribute('disabled');

请参阅https://testing-library.com/docs/react-testing-library/example-intro