Jsdom: Error: No implementado: HTMLFormElement.prototype.submit

Creado en 10 ago. 2017  ·  21Comentarios  ·  Fuente: jsdom/jsdom

Error

HTMLInputElement {} HTMLInputElement {}
Error: Not implemented: HTMLFormElement.prototype.submit
    at module.exports (/home/xlmnxp/Documents/Nodejs/DownFrom99/node_modules/jsdom/lib/jsdom/browser/not-implemented.js:9:17)
    at HTMLFormElementImpl.submit (/home/xlmnxp/Documents/Nodejs/DownFrom99/node_modules/jsdom/lib/jsdom/living/nodes/HTMLFormElement-impl.js:68:5)
    at HTMLFormElement.submit (/home/xlmnxp/Documents/Nodejs/DownFrom99/node_modules/jsdom/lib/jsdom/living/generated/HTMLFormElement.js:18:21)
    at /home/xlmnxp/Documents/Nodejs/DownFrom99/app.js:12:10
    at process._tickCallback (internal/process/next_tick.js:109:7) undefined
import { JSDOM } from "jsdom";

JSDOM.fromURL("http://localhost/").then((dom:JSDOM) => {
    let document = dom.window.document;
    let window = dom.window;

    let form = <HTMLFormElement> document.querySelector("form");
    let urlField = <HTMLInputElement> document.querySelector("input[name='formvalue']");
    let submitButton = <HTMLInputElement> document.querySelector("input[type='submit']");

    console.log(submitButton,urlField)

    urlField.value = "https://www.youtube.com/watch?v=RWjDLfx8Lww";

    form.submit()

})

Comentario más útil

Me encontré con esto al escribir pruebas usando Jest.
Mi solución:

window.HTMLFormElement.prototype.submit = () => {}

Agregué esto antes de montar mi componente en el caso de prueba.
Al menos mantiene limpia mi consola.

Todos 21 comentarios

Sí, de hecho, el envío de formularios no está implementado. Esto está funcionando como se esperaba.

@runbb , ¿encontraste otra solución para esto? Estoy intentando hacer lo mismo.

@domenic ¿Tiene alguna idea sobre cómo lograr esta funcionalidad? ¿Quizás otra biblioteca?

@stefanbuck no :(

@domenic, ¿hay alguna razón por la que esto no se haya implementado? ¿Estaría abierto a una solicitud de extracción para implementar esto?

Consulte https://github.com/jsdom/jsdom#unimplemented -parts-of-the-web-platform. Se trata de navegación y, por lo tanto, es una empresa enorme. Puede intentarlo, pero comprenda que debe implementar básicamente todo https://html.spec.whatwg.org/multipage/browsing-the-web.html.

@domenic sería bueno desactivar este mensaje de error.

Puede hacerlo; vea el archivo Léame en jsdomErrors.

¿Todavía es posible implementar el manejo de las entradas cuando se envía el formulario?
event.target[name] no están definidos.

Mi solución alternativa por ahora es form.dispatchEvent(new Event('submit'));

Me encontré con esto al escribir pruebas usando Jest.
Mi solución:

window.HTMLFormElement.prototype.submit = () => {}

Agregué esto antes de montar mi componente en el caso de prueba.
Al menos mantiene limpia mi consola.

Logré silenciar los errores haciendo:

describe('submit', () => {
  let emit;

  beforeAll(() => {
    ({ emit } = window._virtualConsole);
  });

  beforeEach(() => {
    window._virtualConsole.emit = jest.fn();
  });

  afterAll(() => {
    window._virtualConsole.emit = emit;
  });

  it('should handle submit ', () => {
    ...
  });
});

Me encontré con esto al escribir pruebas usando Jest.
Mi solución:

window.HTMLFormElement.prototype.submit = () => {}

Agregué esto antes de montar mi componente en el caso de prueba.
Al menos mantiene limpia mi consola.

¡Hola! Me gusta tu solución pero no estoy seguro de dónde hacer eso, ¿crees que podrías ayudar? Tengo el siguiente código: (vea que agregué su "corrección" como la primera declaración en main ())

const jsdom = require("jsdom");
const { JSDOM } = jsdom;

JSDOM.fromFile("index.html", null).then(dom => {
    main(dom.window);
});

function main(window){

  window.HTMLFormElement.prototype.submit = () => {}

  var oldAlert = window.alert;
  window.alert = function() {
    console.log("Alert fired with arguments: " + arguments);
    oldAlert.apply(window, arguments);
  };

  window.document.getElementsByTagName("button")[0].click();

}

pero sigue recaudando lo mismo Error: Not implemented: HTMLFormElement.prototype.submit

Solución posible:

// Following code mocks window.console.error
// to ignore the "Not implemented: HTMLFormElement.prototype.submit".
//
// Problem: We use "form.onsubmit" event listener in some tests,
// but HTMLFormElement.prototype.submit is not implemented in JSDOM,
// although the tests are passing and handler fires.
//
// More:
// https://github.com/jsdom/jsdom/issues/1937
// https://github.com/facebook/jest/issues/5223#issuecomment-489422244

let origErrorConsole;

beforeEach(() => {
  origErrorConsole = window.console.error;

  window.console.error = (...args) => {
    const firstArg = args.length > 0 && args[0];

    const shouldBeIgnored =
      firstArg &&
      typeof firstArg === 'string' &&
      firstArg.includes('Not implemented: HTMLFormElement.prototype.submit');

    if (!shouldBeIgnored) {
      origErrorConsole(...args);
    }
  }
})

afterEach(() => {
  window.console.error = origErrorConsole;
})

Si no le importa el submit , también puede deshabilitar el envío del formulario con

<form onsubmit="return false;">

No más mensaje de error

Solución posible:

// Following code mocks window.console.error
// to ignore the "Not implemented: HTMLFormElement.prototype.submit".
//
// Problem: We use "form.onsubmit" event listener in some tests,
// but HTMLFormElement.prototype.submit is not implemented in JSDOM,
// although the tests are passing and handler fires.
//
// More:
// https://github.com/jsdom/jsdom/issues/1937
// https://github.com/facebook/jest/issues/5223#issuecomment-489422244

let origErrorConsole;

beforeEach(() => {
  origErrorConsole = window.console.error;

  window.console.error = (...args) => {
    const firstArg = args.length > 0 && args[0];

    const shouldBeIgnored =
      firstArg &&
      typeof firstArg === 'string' &&
      firstArg.includes('Not implemented: HTMLFormElement.prototype.submit');

    if (!shouldBeIgnored) {
      origErrorConsole(...args);
    }
  }
})

afterEach(() => {
  window.console.error = origErrorConsole;
})

Esta solución rompe la pila de errores reales y será más difícil encontrarlos.

Antes
image

Después
image

Si usa una consola virtual y escucha "jsdomError" s, debería obtener un objeto de excepción con un seguimiento de pila.

@domenic , ¿podría mostrarnos cómo usar una consola virtual desde el archivo de prueba?

Sugerimos que el archivo de prueba sea el siguiente

import React from 'react'

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

import ComponentWithSubmit from './ComponentWithSubmit'

test('Component with form', () => {
  const {getByText} = render(<ComponentWithSubmit />)
  expect(getByText('I am inside form')).toBeInTheDocument()
})

PD: hay broma como corredor de pruebas

Lo siento, tendrás que pedir ayuda a Jest sobre cómo usar Jest. Jsdom solo puede proporcionar soporte para jsdom en sí, no para ningún paquete que use jsdom como dependencia.

Tenía un componente que usaba un formulario pero no usaba enviar en el formulario y seguía viendo este error. Lo resolví agregando type = "button" a mis otros botones dentro del formulario.

¿Fue útil esta página
0 / 5 - 0 calificaciones