【问题标题】:Error: Not implemented: HTMLFormElement.prototype.submit错误:未实现:HTMLFormElement.prototype.submit
【发布时间】:2020-09-24 17:06:31
【问题描述】:

这就是我的测试用例的样子:

const renderCard = ({
  onSubmit = jest.fn(),
}: RenderCardParams = {}) => {
  return render(
        <Card title={title} onSubmit={onSubmit}>
          <Button type="submit">Save</Button>
        </Card>,
  );
}; 

it("should invoke onSubmit when form is submitted", async () => {
      const onSubmit = jest.fn();
      window.HTMLFormElement.prototype.submit = () => {};
      const { getByText } = renderCard({ onSubmit });
      const button = getByText("Save").closest("button");
      if (button) {
        fireEvent.click(button);
      }
      await wait(() => expect(onSubmit).toHaveBeenCalled());
 });

我收到“错误:未实现:HTMLFormElement.prototype.submit”。我尝试了这里提到的解决方案 https://github.com/jsdom/jsdom/issues/1937 ,但没有奏效。我不想消除错误,但要正确实施测试。谢谢你。

【问题讨论】:

    标签: reactjs typescript forms jestjs react-testing-library


    【解决方案1】:

    我遇到了类似的问题,通过调用event.preventDefault() 方法得到了解决。

    我认为这需要在您的“onSubmit”函数中调用

    const onSubmit = jest.fn(e => e.preventDefault());
    

    编辑:哇哦忘了调用它! ?

    【讨论】:

    • 谢谢@doughellowell。可悲的是,这在上述情况下不起作用。错误仍然存​​在。
    • 这对我也不起作用,但在测试块中使用 mockImplementation 可以。
    • 我不知道为什么,我不想知道为什么,我不想想知道为什么,但这实际上解决了问题
    • 对我来说这有效submit = jest.fn().mockImplementation((e) =&gt; e.preventDefault());
    • 缺少括号submit = jest.fn(e =&gt; e.preventDefault())
    【解决方案2】:

    我不得不模拟我的 onSubmit 函数的实现来清除错误,阻止默认提交行为。

    试试这样的:

    const onSubmit = jest.fn();
    
    
    it("should invoke onSubmit when form is submitted", async () => {
          onSubmit.mockImplementation(event => {
            event.preventDefault();
          });
    
          const { getByText } = renderCard({ onSubmit });
          const button = getByText("Save").closest("button");
          if (button) {
            fireEvent.click(button);
          }
          await wait(() => expect(onSubmit).toHaveBeenCalled());
     });
    

    您可以在 React herehere 中阅读有关 event.preventDefault 的更多信息。

    对我有用的其他方法是使用 RTL 的 fireEvent.submit,尽管您需要获得一个表单元素才能使其工作。假设您的Card 实现以getByRole 可识别的方式呈现表单,您也可以尝试以下操作:

    fireEvent.submit(screen.getByRole('form'));
    

    这将代替模拟按钮单击,这在您的情况下可能是可以接受的,因为您似乎是在测试表单提交而不是按钮的行为。

    【讨论】:

      猜你喜欢
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      相关资源
      最近更新 更多