capricorn86 / happy-dom

A JavaScript implementation of a web browser without its graphical user interface
MIT License
3.39k stars 204 forks source link

When submitting a form, the `event.target` is not the proper node. #1544

Open juandiegombr opened 1 month ago

juandiegombr commented 1 month ago

Describe the bug When submitting a form, the form element obtained via the event.target is different from the form element obtained via document.getElementById(formId) or document.forms.namedItem(formId)

To Reproduce This test should pass:

it('submit target node is equal to node retrieved from document', () => {
    const element = <HTMLFormElement>document.createElement('form');
    element.setAttribute('id', 'form-id');
    element.innerHTML = `
                        <div>
                                <input type="text" name="text1">
                        </div>
                `;

    document.body.appendChild(element);

    let submitEvent: Event | null = null;
    let target: EventTarget | null = null;

    element.addEventListener('submit', (event: Event) => {
        submitEvent = event;
        target = event.target;
    });

    element.action = 'https://localhost:3000';
    element.noValidate = true;
    element.requestSubmit();

    const form = document.forms.namedItem('form-id');
    expect(form === target).toBeTruthy();
});

Expected behavior Both nodes should be the same.

Additional context This problem came up when using conform-to/react. In the source code of this library makes this comparison. While in the browser works well it fails if a try to test it.

https://github.com/edmundhung/conform/blob/main/packages/conform-dom/form.ts#L784-L794

juandiegombr commented 1 month ago

I am trying to figure out how to solve this issue but I don't find in the source code how the node is injected in the event.