diff --git a/docs/guide/browser/interactivity-api.md b/docs/guide/browser/interactivity-api.md index c187e3d7b574..b10169e3635f 100644 --- a/docs/guide/browser/interactivity-api.md +++ b/docs/guide/browser/interactivity-api.md @@ -29,6 +29,29 @@ Almost every `userEvent` method inherits its provider options. To see all availa ``` ::: +## userEvent.setup + +- **Type:** `() => UserEvent` + +Creates a new user event instance. This is useful if you need to keep the state of keyboard to press and release buttons correctly. + +::: warning +Unlike `@testing-library/user-event`, the default `userEvent` instance from `@vitest/browser/context` is created once, not every time its methods are called! You can see the difference in how it works in this snippet: + +```ts +import { userEvent as vitestUserEvent } from '@vitest/browser/context' +import { userEvent as originalUserEvent } from '@testing-library/user-event' + +await vitestUserEvent.keyboard('{Shift}') // press shift without releasing +await vitestUserEvent.keyboard('{/Shift}') // releases shift + +await originalUserEvent.keyboard('{Shift}') // press shift without releasing +await originalUserEvent.keyboard('{/Shift}') // DID NOT release shift because the state is different +``` + +This behaviour is more useful because we do not emulate the keyboard, we actually press the Shift, so keeping the original behaviour would cause unexpected issues when typing in the field. +::: + ## userEvent.click - **Type:** `(element: Element, options?: UserEventClickOptions) => Promise` @@ -163,7 +186,7 @@ test('trigger keystrokes', async () => { References: -- [Playwright `locator.press` API](https://playwright.dev/docs/api/class-locator#locator-press) +- [Playwright `Keyboard` API](https://playwright.dev/docs/api/class-keyboard) - [WebdriverIO `action('key')` API](https://webdriver.io/docs/api/browser/action#key-input-source) - [testing-library `type` API](https://testing-library.com/docs/user-event/utility/#type) @@ -194,7 +217,7 @@ test('tab works', async () => { References: -- [Playwright `locator.press` API](https://playwright.dev/docs/api/class-locator#locator-press) +- [Playwright `Keyboard` API](https://playwright.dev/docs/api/class-keyboard) - [WebdriverIO `action('key')` API](https://webdriver.io/docs/api/browser/action#key-input-source) - [testing-library `tab` API](https://testing-library.com/docs/user-event/convenience/#tab) diff --git a/packages/browser/context.d.ts b/packages/browser/context.d.ts index 167af84420ab..7ea085dc1a3c 100644 --- a/packages/browser/context.d.ts +++ b/packages/browser/context.d.ts @@ -49,6 +49,14 @@ export interface BrowserCommands { } export interface UserEvent { + /** + * Creates a new user event instance. This is useful if you need to keep the + * state of keyboard to press and release buttons correctly. + * + * **Note:** Unlike `@testing-library/user-event`, the default `userEvent` instance + * from `@vitest/browser/context` is created once, not every time its methods are called! + * @see {@link https://vitest.dev/guide/browser/interactivity-api.html#userevent-setup} + */ setup: () => UserEvent /** * Click on an element. Uses provider's API under the hood and supports all its options. @@ -103,7 +111,7 @@ export interface UserEvent { * await userEvent.keyboard('foo') // translates to: f, o, o * await userEvent.keyboard('{{a[[') // translates to: {, a, [ * await userEvent.keyboard('{Shift}{f}{o}{o}') // translates to: Shift, f, o, o - * @see {@link https://playwright.dev/docs/api/class-locator#locator-press} Playwright API + * @see {@link https://playwright.dev/docs/api/class-keyboard} Playwright API * @see {@link https://webdriver.io/docs/api/browser/keys} WebdriverIO API * @see {@link https://testing-library.com/docs/user-event/keyboard} testing-library API */ @@ -129,7 +137,7 @@ export interface UserEvent { clear: (element: Element) => Promise /** * Sends a `Tab` key event. Uses provider's API under the hood. - * @see {@link https://playwright.dev/docs/api/class-locator#locator-press} Playwright API + * @see {@link https://playwright.dev/docs/api/class-keyboard} Playwright API * @see {@link https://webdriver.io/docs/api/element/keys} WebdriverIO API * @see {@link https://testing-library.com/docs/user-event/convenience/#tab} testing-library API */ diff --git a/packages/browser/src/client/tester/context.ts b/packages/browser/src/client/tester/context.ts index b23d36df426e..881dd808b9e8 100644 --- a/packages/browser/src/client/tester/context.ts +++ b/packages/browser/src/client/tester/context.ts @@ -84,65 +84,83 @@ function getParent(el: Element) { return parent } -export const userEvent: UserEvent = { - // TODO: actually setup userEvent with config options - setup() { - return userEvent - }, - click(element: Element, options: UserEventClickOptions = {}) { - const css = convertElementToCssSelector(element) - return triggerCommand('__vitest_click', css, options) - }, - dblClick(element: Element, options: UserEventClickOptions = {}) { - const css = convertElementToCssSelector(element) - return triggerCommand('__vitest_dblClick', css, options) - }, - tripleClick(element: Element, options: UserEventClickOptions = {}) { - const css = convertElementToCssSelector(element) - return triggerCommand('__vitest_tripleClick', css, options) - }, - selectOptions(element, value) { - const values = provider === 'webdriverio' - ? getWebdriverioSelectOptions(element, value) - : getSimpleSelectOptions(element, value) - const css = convertElementToCssSelector(element) - return triggerCommand('__vitest_selectOptions', css, values) - }, - type(element: Element, text: string, options: UserEventTypeOptions = {}) { - const css = convertElementToCssSelector(element) - return triggerCommand('__vitest_type', css, text, options) - }, - clear(element: Element) { - const css = convertElementToCssSelector(element) - return triggerCommand('__vitest_clear', css) - }, - tab(options: UserEventTabOptions = {}) { - return triggerCommand('__vitest_tab', options) - }, - keyboard(text: string) { - return triggerCommand('__vitest_keyboard', text) - }, - hover(element: Element) { - const css = convertElementToCssSelector(element) - return triggerCommand('__vitest_hover', css) - }, - unhover(element: Element) { - const css = convertElementToCssSelector(element.ownerDocument.body) - return triggerCommand('__vitest_hover', css) - }, +function createUserEvent(): UserEvent { + const keyboard = { + unreleased: [] as string[], + } - // non userEvent events, but still useful - fill(element: Element, text: string, options) { - const css = convertElementToCssSelector(element) - return triggerCommand('__vitest_fill', css, text, options) - }, - dragAndDrop(source: Element, target: Element, options = {}) { - const sourceCss = convertElementToCssSelector(source) - const targetCss = convertElementToCssSelector(target) - return triggerCommand('__vitest_dragAndDrop', sourceCss, targetCss, options) - }, + return { + setup() { + return createUserEvent() + }, + click(element: Element, options: UserEventClickOptions = {}) { + const css = convertElementToCssSelector(element) + return triggerCommand('__vitest_click', css, options) + }, + dblClick(element: Element, options: UserEventClickOptions = {}) { + const css = convertElementToCssSelector(element) + return triggerCommand('__vitest_dblClick', css, options) + }, + tripleClick(element: Element, options: UserEventClickOptions = {}) { + const css = convertElementToCssSelector(element) + return triggerCommand('__vitest_tripleClick', css, options) + }, + selectOptions(element, value) { + const values = provider === 'webdriverio' + ? getWebdriverioSelectOptions(element, value) + : getSimpleSelectOptions(element, value) + const css = convertElementToCssSelector(element) + return triggerCommand('__vitest_selectOptions', css, values) + }, + async type(element: Element, text: string, options: UserEventTypeOptions = {}) { + const css = convertElementToCssSelector(element) + const { unreleased } = await triggerCommand<{ unreleased: string[] }>( + '__vitest_type', + css, + text, + { ...options, unreleased: keyboard.unreleased }, + ) + keyboard.unreleased = unreleased + }, + clear(element: Element) { + const css = convertElementToCssSelector(element) + return triggerCommand('__vitest_clear', css) + }, + tab(options: UserEventTabOptions = {}) { + return triggerCommand('__vitest_tab', options) + }, + async keyboard(text: string) { + const { unreleased } = await triggerCommand<{ unreleased: string[] }>( + '__vitest_keyboard', + text, + keyboard, + ) + keyboard.unreleased = unreleased + }, + hover(element: Element) { + const css = convertElementToCssSelector(element) + return triggerCommand('__vitest_hover', css) + }, + unhover(element: Element) { + const css = convertElementToCssSelector(element.ownerDocument.body) + return triggerCommand('__vitest_hover', css) + }, + + // non userEvent events, but still useful + fill(element: Element, text: string, options) { + const css = convertElementToCssSelector(element) + return triggerCommand('__vitest_fill', css, text, options) + }, + dragAndDrop(source: Element, target: Element, options = {}) { + const sourceCss = convertElementToCssSelector(source) + const targetCss = convertElementToCssSelector(target) + return triggerCommand('__vitest_dragAndDrop', sourceCss, targetCss, options) + }, + } } +export const userEvent: UserEvent = createUserEvent() + function getWebdriverioSelectOptions(element: Element, value: string | string[] | HTMLElement[] | HTMLElement) { const options = [...element.querySelectorAll('option')] as HTMLOptionElement[] diff --git a/packages/browser/src/node/commands/keyboard.ts b/packages/browser/src/node/commands/keyboard.ts index 08fd74292e28..ec3fe9a24f38 100644 --- a/packages/browser/src/node/commands/keyboard.ts +++ b/packages/browser/src/node/commands/keyboard.ts @@ -3,12 +3,16 @@ import { defaultKeyMap } from '@testing-library/user-event/dist/esm/keyboard/key import type { BrowserProvider } from 'vitest/node' import { PlaywrightBrowserProvider } from '../providers/playwright' import { WebdriverBrowserProvider } from '../providers/webdriver' -import type { UserEvent } from '../../../context' import type { UserEventCommand } from './utils' -export const keyboard: UserEventCommand = async ( +export interface KeyboardState { + unreleased: string[] +} + +export const keyboard: UserEventCommand<(text: string, state: KeyboardState) => Promise<{ unreleased: string[] }>> = async ( context, text, + state, ) => { function focusIframe() { if ( @@ -28,7 +32,10 @@ export const keyboard: UserEventCommand = async ( await context.browser.execute(focusIframe) } + const pressed = new Set(state.unreleased) + await keyboardImplementation( + pressed, context.provider, context.contextId, text, @@ -52,17 +59,20 @@ export const keyboard: UserEventCommand = async ( }, true, ) + + return { + unreleased: Array.from(pressed), + } } export async function keyboardImplementation( + pressed: Set, provider: BrowserProvider, contextId: string, text: string, selectAll: () => Promise, skipRelease: boolean, ) { - const pressed = new Set() - if (provider instanceof PlaywrightBrowserProvider) { const page = provider.getPage(contextId) const actions = parseKeyDef(defaultKeyMap, text) @@ -145,7 +155,10 @@ export async function keyboardImplementation( } } - await keyboard.perform(skipRelease) + // seems like webdriverio doesn't release keys automatically if skipRelease is true and all events are keyUp + const allRelease = keyboard.toJSON().actions.every(action => action.type === 'keyUp') + + await keyboard.perform(allRelease ? false : skipRelease) } return { diff --git a/packages/browser/src/node/commands/type.ts b/packages/browser/src/node/commands/type.ts index ff79fb7e9c34..c211d1e6a697 100644 --- a/packages/browser/src/node/commands/type.ts +++ b/packages/browser/src/node/commands/type.ts @@ -11,6 +11,7 @@ export const type: UserEventCommand = async ( options = {}, ) => { const { skipClick = false, skipAutoClose = false } = options + const unreleased = new Set(Reflect.get(options, 'unreleased') as string[] ?? []) if (context.provider instanceof PlaywrightBrowserProvider) { const { iframe } = context @@ -21,6 +22,7 @@ export const type: UserEventCommand = async ( } await keyboardImplementation( + unreleased, context.provider, context.contextId, text, @@ -37,6 +39,7 @@ export const type: UserEventCommand = async ( } await keyboardImplementation( + unreleased, context.provider, context.contextId, text, @@ -52,4 +55,8 @@ export const type: UserEventCommand = async ( else { throw new TypeError(`Provider "${context.provider.name}" does not support typing`) } + + return { + unreleased: Array.from(unreleased), + } } diff --git a/packages/browser/src/node/plugins/pluginContext.ts b/packages/browser/src/node/plugins/pluginContext.ts index 6802ca12e874..6546d5b48a03 100644 --- a/packages/browser/src/node/plugins/pluginContext.ts +++ b/packages/browser/src/node/plugins/pluginContext.ts @@ -94,10 +94,17 @@ function getUserEvent(provider: BrowserProvider) { } // TODO: have this in a separate file return `{ - ...__vitest_user_event__, - fill: async (element, text) => { - await __vitest_user_event__.clear(element) - await __vitest_user_event__.type(element, text) + ..._userEventSetup, + setup() { + const userEvent = __vitest_user_event__.setup() + userEvent.setup = this.setup + userEvent.fill = this.fill.bind(userEvent) + userEvent.dragAndDrop = this.dragAndDrop + return userEvent + }, + async fill(element, text) { + await this.clear(element) + await this.type(element, text) }, dragAndDrop: async () => { throw new Error('Provider "preview" does not support dragging elements') @@ -115,5 +122,5 @@ async function getUserEventImport(provider: BrowserProvider, resolve: (id: strin } return `import { userEvent as __vitest_user_event__ } from '${slash( `/@fs/${resolved.id}`, - )}'` + )}'\nconst _userEventSetup = __vitest_user_event__.setup()\n` } diff --git a/test/browser/test/userEvent.test.ts b/test/browser/test/userEvent.test.ts index 77363addd2e3..44351d778fab 100644 --- a/test/browser/test/userEvent.test.ts +++ b/test/browser/test/userEvent.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, test, vi } from 'vitest' -import { server, userEvent } from '@vitest/browser/context' +import { userEvent as _uE, server } from '@vitest/browser/context' import '../src/button.css' beforeEach(() => { @@ -7,6 +7,8 @@ beforeEach(() => { document.body.replaceChildren() }) +const userEvent = _uE.setup() + describe('userEvent.click', () => { test('correctly clicks a button', async () => { const button = document.createElement('button') @@ -347,11 +349,11 @@ describe.each(inputLike)('userEvent.type', (getElement) => { test('repeating without manual up works correctly', async () => { const { input, keydown, keyup, value } = createTextInput() - await userEvent.type(input, '{a>3}4') - expect(value()).toBe('aaa4') + const userEvent = _uE.setup() + await userEvent.type(input, '{a>2}4') + expect(value()).toBe('aa4') expect(keydown).toEqual([ - 'a', 'a', 'a', '4', @@ -366,6 +368,7 @@ describe.each(inputLike)('userEvent.type', (getElement) => { test('repeating with manual up works correctly', async () => { const { input, keydown, keyup, value } = createTextInput() + const userEvent = _uE.setup() await userEvent.type(input, '{a>3/}4') expect(value()).toBe('aaa4') @@ -385,6 +388,7 @@ describe.each(inputLike)('userEvent.type', (getElement) => { test('repeating with disabled up works correctly', async () => { const { input, keydown, keyup, value } = createTextInput() + const userEvent = _uE.setup() await userEvent.type(input, '{a>3}4', { skipAutoClose: true, }) @@ -406,6 +410,7 @@ describe.each(inputLike)('userEvent.type', (getElement) => { const shadowRoot = createShadowRoot() const { input, keydown, value } = createTextInput(shadowRoot) + const userEvent = _uE.setup() await userEvent.type(input, 'Hello') expect(value()).toBe('Hello') expect(keydown).toEqual([ @@ -557,6 +562,7 @@ describe('userEvent.keyboard', async () => { ]) }) + // looks like wdio doesn't support releasing Enter on its own test('should not auto release', async () => { const spyKeydown = vi.fn() const spyKeyup = vi.fn() @@ -569,8 +575,7 @@ describe('userEvent.keyboard', async () => { expect(spyKeydown).toHaveBeenCalledOnce() expect(spyKeyup).not.toHaveBeenCalled() await userEvent.keyboard('{/Enter}') - // userEvent doesn't fire any event here, but should we? - expect(spyKeyup).not.toHaveBeenCalled() + expect(spyKeyup).toHaveBeenCalled() }) test('standalone keyboard works correctly with active input', async () => {