【问题标题】:Unit test form submission with data using react testing library使用反应测试库提交带有数据的单元测试表单
【发布时间】:2020-08-15 15:16:57
【问题描述】:

我有一个带有表单的反应组件。如果表单使用正确的数据提交,我想进行单元测试(使用 jest 和 RTL)。这是我的组件和单元测试方法:

组件:

class AddDeviceModal extends Component {
  handleOnSave(event) {
    const { deviceName } = event.target;
    const formData = {
      deviceName: deviceName.value,
    };
    this.props.onSave(formData);
  }

  render() {
    return (
      <Form onSubmit={this.handleOnSave}>
        <Form.Label>Device Name</Form.Label>
        <Form.Control name="deviceName" placeholder="Device Name" required />
        <Button type="submit">Save Device</Button>
      </Form>
    );
  }
}

单元测试:

it("Test form submit and validation", () => {
  const handleSave = jest.fn();
  const props = {
    onSave: handleSave,
  };
  render(<AddDeviceModal {...props} />);
  const deviceNameInput = screen.getByPlaceholderText(/device name/i);
  fireEvent.change(deviceNameInput, { target: { value: "AP VII C2230" } });
  fireEvent.click(getByText(/save device/i));
});

但是,在handleOnSave() 中,我收到错误,因为deviceNameundefined。由于某种原因,它无法从event.target 获取文本框值。我在上面的代码中做错了吗?需要帮助来解决此问题。

【问题讨论】:

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


    【解决方案1】:

    您在尝试直接从event.target 访问输入时遇到的问题。您应该从event.target.elements 访问它:https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements

    function handleOnSave(event) {
      event.preventDefault();
      const { deviceName } = event.target.elements;
      const formData = {
        deviceName: deviceName.value
      };
    
      // this will log the correct formData even in tests now
      console.log(formData);
      this.props.onSave(formData);
    }
    

    这是你的测试:

    it("Test form submit and validation", () => {
      const { getByPlaceholderText, getByText } = render(<App />);
      const deviceNameInput = getByPlaceholderText(/device name/i);
    
      fireEvent.change(deviceNameInput, { target: { value: "AP VII C2230" } });
      fireEvent.click(getByText(/Save Device/i));
    });
    

    我创建了一个代码框,您可以在其中看到这一点:https://codesandbox.io/s/form-submit-react-testing-library-45pt8?file=/src/App.js

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 2022-10-19
      • 2014-06-28
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      相关资源
      最近更新 更多