簡體   English   中英

使用反應測試庫提交帶有數據的單元測試表單

[英]Unit test form submission with data using react testing library

我有一個帶有表單的反應組件。 如果表單使用正確的數據提交,我想進行單元測試(使用 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()中,我收到錯誤,因為deviceName is undefined 由於某種原因,它無法從event.target獲取文本框值。 我在上面的代碼中做錯了嗎? 需要幫助來解決此問題。

嘗試直接從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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM