From 3207debb67591d63932f6a4228e2d21d7525450c Mon Sep 17 00:00:00 2001 From: Andrew Scott Date: Wed, 8 Mar 2023 20:24:03 -0800 Subject: [PATCH] fix: return wrapper error from DOMWrapper ctor if element is nullish (fixes #1984) (#1996) --- docs/guide/extending-vtu/plugins.md | 6 +----- src/domWrapper.ts | 5 ++++- src/wrapperFactory.ts | 4 +++- tests/exists.spec.ts | 7 ++++++- 4 files changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/guide/extending-vtu/plugins.md b/docs/guide/extending-vtu/plugins.md index 8e908f07f..4229a122e 100644 --- a/docs/guide/extending-vtu/plugins.md +++ b/docs/guide/extending-vtu/plugins.md @@ -109,11 +109,7 @@ const DataTestIdPlugin = (wrapper) => { function findByTestId(selector) { const dataSelector = `[data-testid='${selector}']` const element = wrapper.element.querySelector(dataSelector) - if (element) { - return new DOMWrapper(element) - } - - return createWrapperError('DOMWrapper') + return new DOMWrapper(element) } return { diff --git a/src/domWrapper.ts b/src/domWrapper.ts index ccd3a2f9b..b7b9450a9 100644 --- a/src/domWrapper.ts +++ b/src/domWrapper.ts @@ -11,7 +11,10 @@ import { isRefSelector } from './utils' import { createWrapperError } from './errorWrapper' export class DOMWrapper extends BaseWrapper { - constructor(element: NodeType) { + constructor(element: NodeType | null | undefined) { + if (!element) { + return createWrapperError('DOMWrapper') + } super(element) // plugins hook config.plugins.DOMWrapper.extend(this) diff --git a/src/wrapperFactory.ts b/src/wrapperFactory.ts index af1cd04d9..429773e30 100644 --- a/src/wrapperFactory.ts +++ b/src/wrapperFactory.ts @@ -7,7 +7,9 @@ export enum WrapperType { VueWrapper } -type DOMWrapperFactory = (element: T) => DOMWrapperType +type DOMWrapperFactory = ( + element: T | null | undefined +) => DOMWrapperType type VueWrapperFactory = ( app: App | null, vm: T, diff --git a/tests/exists.spec.ts b/tests/exists.spec.ts index 706d4e050..11d28bdf8 100644 --- a/tests/exists.spec.ts +++ b/tests/exists.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { h, defineComponent } from 'vue' -import { mount } from '../src' +import { DOMWrapper, mount } from '../src' describe('exists', () => { it('returns false when element does not exist', () => { @@ -50,4 +50,9 @@ describe('exists', () => { await wrapper.setProps({ hide: true }) expect(child.exists()).toBe(false) }) + + it('returns false when wrapper is manually constructed against nullish element', () => { + const wrapper = new DOMWrapper(null) + expect(wrapper.exists()).toBe(false) + }) })