fix: handle null options in `addEventHandler` #9371 (#9372) · vitest-dev/vitest@40841ff

File tree

2 files changed

lines changed

  • packages/vitest/src/integrations/env

  • test/core/test/environments

2 files changed

lines changed

Original file line numberDiff line numberDiff line change

@@ -328,7 +328,7 @@ function patchAddEventListener(window: DOMWindow) {

328328

callback: EventListenerOrEventListenerObject | null,

329329

options?: AddEventListenerOptions | boolean,

330330

) {

331-

if (typeof options === 'object' && options.signal != null) {

331+

if (typeof options === 'object' && options?.signal != null) {

332332

const { signal, ...otherOptions } = options

333333

// - this happens because AbortSignal is provided by Node.js,

334334

// but jsdom APIs require jsdom's AbortSignal, while Node APIs

Original file line numberDiff line numberDiff line change

@@ -226,6 +226,20 @@ test('can pass down the same abort signal many times without a warning', ({ onTe

226226

}))

227227

})

228228
229+

test('DOM APIs addEventListener allow null as third parameter', () => {

230+

const element = document.createElement('div')

231+

document.body.append(element)

232+

const spy = vi.fn()

233+
234+

// eslint-disable-next-line ts/ban-ts-comment

235+

// @ts-expect-error

236+

element.addEventListener('click', spy, null)

237+
238+

element.click()

239+
240+

expect(spy).toHaveBeenCalledTimes(1)

241+

})

242+
229243

test('atob and btoa are available', () => {

230244

expect(atob('aGVsbG8gd29ybGQ=')).toBe('hello world')

231245

expect(btoa('hello world')).toBe('aGVsbG8gd29ybGQ=')