capricorn86 / happy-dom

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

React `onClick` handler with `preventDefault()` on an anchor tag does not prevent navigation #1464

Closed amitdahan closed 2 weeks ago

amitdahan commented 2 weeks ago

Describe the bug

An <a href="https://example.com">Click me</a> tag with a click handler that invokes event.preventDefault() should prevent the subsequent navigation.

When doing this with pure DOM APIs:

const anchor = document.createElement('a');
anchor.href = 'http://example.com';
anchor.textContent = 'Click me';
anchor.addEventListener('click', (e) => e.preventDefault());
document.body.appendChild(anchor);

anchor.click();
expect(location.href).not.toBe('http://example.com');

This passes.

When doing the same, but passing through React (and its synthetic event handling):

render(
  <a href="http://example.com" onClick={(e) => e.preventDefault()}>
    Click me
  </a>
);

screen.getByRole('link').click();
expect(location.href).not.toBe('http://example.com');

This fails, but should pass.

To Reproduce

https://stackblitz.com/edit/stackblitz-starters-x99sjj?file=package.json

The "Pure DOM"-based test passes The React-based one fails

Expected behavior The React test should pass

Additional context In real DOM and in JSDom this works as expected