vitest-dev / vitest

Next generation testing framework powered by Vite.
https://vitest.dev
MIT License
12.64k stars 1.13k forks source link

Global error listeners not called for thrown errors #6292

Open with-heart opened 1 month ago

with-heart commented 1 month ago

Describe the bug

When registering a global error listener using addEventListener with both jsdom and happy-dom environments, the listener is not called by an error being thrown.

Dispatching an ErrorEvent using dispatchEvent does cause the listener to be called.

Reproduction

Failing throw test: https://stackblitz.com/edit/vitest-dev-vitest-eujrhm?file=test%2Fthrow.test.ts

Passing dispatchEvent test: https://stackblitz.com/edit/vitest-dev-vitest-eujrhm?file=test%2Fdispatch.test.ts

System Info

System:
    OS: macOS 14.5
    CPU: (10) arm64 Apple M1 Max
    Memory: 26.91 GB / 64.00 GB
    Shell: 5.9 - /opt/homebrew/bin/zsh
  Binaries:
    Node: 20.15.1 - ~/.local/state/fnm_multishells/82617_1722983370322/bin/node
    Yarn: 1.22.22 - ~/Library/pnpm/yarn
    npm: 10.7.0 - ~/.local/state/fnm_multishells/82617_1722983370322/bin/npm
    pnpm: 9.6.0 - ~/Library/pnpm/pnpm
    bun: 1.1.20 - /opt/homebrew/bin/bun
    Watchman: 2024.07.15.00 - /opt/homebrew/bin/watchman
  Browsers:
    Chrome: 127.0.6533.89
    Safari: 17.5
  npmPackages:
    vitest: ^2.0.3 => 2.0.3

Used Package Manager

yarn

Validations

sheremet-va commented 1 month ago

Failing throw test: stackblitz.com/edit/vitest-dev-vitest-eujrhm?file=test/throw.test.ts

The error you threw is correctly caught because there is a try/catch handler for every test, so it's not unhandled. I don't think you can trigger a global error event in tests because even file imports have guards, you'd need to detach the throw from the current context somehow, and the only way I know how it is by throwing an error asynchronously and not awaiting the promise, but that would be unhandledrejection, not error.