Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(browser): userEvent.setup initiates a separate state for userEvent instance #6088

Merged
merged 4 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions docs/guide/browser/interactivity-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>`
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down
12 changes: 10 additions & 2 deletions packages/browser/context.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
*/
Expand All @@ -129,7 +137,7 @@ export interface UserEvent {
clear: (element: Element) => Promise<void>
/**
* 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
*/
Expand Down
130 changes: 74 additions & 56 deletions packages/browser/src/client/tester/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[]

Expand Down
23 changes: 18 additions & 5 deletions packages/browser/src/node/commands/keyboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<UserEvent['keyboard']> = async (
export interface KeyboardState {
unreleased: string[]
}

export const keyboard: UserEventCommand<(text: string, state: KeyboardState) => Promise<{ unreleased: string[] }>> = async (
context,
text,
state,
) => {
function focusIframe() {
if (
Expand All @@ -28,7 +32,10 @@ export const keyboard: UserEventCommand<UserEvent['keyboard']> = async (
await context.browser.execute(focusIframe)
}

const pressed = new Set<string>(state.unreleased)

await keyboardImplementation(
pressed,
context.provider,
context.contextId,
text,
Expand All @@ -52,17 +59,20 @@ export const keyboard: UserEventCommand<UserEvent['keyboard']> = async (
},
true,
)

return {
unreleased: Array.from(pressed),
}
}

export async function keyboardImplementation(
pressed: Set<string>,
provider: BrowserProvider,
contextId: string,
text: string,
selectAll: () => Promise<void>,
skipRelease: boolean,
) {
const pressed = new Set<string>()

if (provider instanceof PlaywrightBrowserProvider) {
const page = provider.getPage(contextId)
const actions = parseKeyDef(defaultKeyMap, text)
Expand Down Expand Up @@ -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 {
Expand Down
7 changes: 7 additions & 0 deletions packages/browser/src/node/commands/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export const type: UserEventCommand<UserEvent['type']> = 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
Expand All @@ -21,6 +22,7 @@ export const type: UserEventCommand<UserEvent['type']> = async (
}

await keyboardImplementation(
unreleased,
context.provider,
context.contextId,
text,
Expand All @@ -37,6 +39,7 @@ export const type: UserEventCommand<UserEvent['type']> = async (
}

await keyboardImplementation(
unreleased,
context.provider,
context.contextId,
text,
Expand All @@ -52,4 +55,8 @@ export const type: UserEventCommand<UserEvent['type']> = async (
else {
throw new TypeError(`Provider "${context.provider.name}" does not support typing`)
}

return {
unreleased: Array.from(unreleased),
}
}
17 changes: 12 additions & 5 deletions packages/browser/src/node/plugins/pluginContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -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`
}
Loading