вариант

Улучшает инструмент Vitest с помощью Midscene для проведения тестирования пользовательского интерфейса с использованием искусственного интеллекта в браузерах (Playwright), на Android (ADB) и iOS (WDA). Позволяет создавать новые проекты, конвертировать существующие, а также формировать/обновлять/отлаживать/запускать тесты типа E2E с использованием команд, сформулированных на естественном языке. Доступные команды: write test, add test, create test, update test, fix test, debug test, run test, e2e test, midscene test, new project, convert project, init project, 写测试, 加测试, 创建测试, 更新测试, 修复测试, 调试测试, 运行测试, 新建工程, 转化工程.

...Расширить все
20
Обновлено время 25 августа 2026 г.

О vitest-midscene-e2e

vitest-midscene-e2e расширяет тестовую платформу Vitest с использованием Midscene для создания тестов пользовательского интерфейса типа «конец-к концу», основанных на искусственном интеллекте и написанных на естественном языке, для веб-платформ (Playwright Chromium), Android (ADB и scrcpy) и iOS (WebDriverAgent). Это решение устраняет проблему хрупкости тестов типа E2E, основанных на селекторах: вместо разбиения пользовательского процесса на сложные действия нажатий и ввода тестировщик передает простой текстовый запрос агенту Midscene, который затем планирует и выполняет необходимые действия. Этот инструмент позволяет создавать новые тестовые проекты, конвертировать существующие, а также создавать, обновлять, отлаживать и запускать тесты с использованием двуязычных (английский и китайский) фраз-триггеров.

Рабочий процесс начинается с клонирования стандартного шаблона с помощью встроенного скрипта, затем происходит сравнение текущего проекта с этим шаблоном и добавление только тех элементов, которые необходимы для выбранных платформ, без перезаписи существующих настроек. Также копируется файл .env.example в .env, чтобы пользователь мог заполнить его необходимыми данными. Основное правило заключается в том, что шаги интерфейса, описанные пользователем, должны реализовываться с использованием основного API aiAct, а не через более детализированные вызовы aiTap/aiInput/aiAssert — таким образом ИИ берет на себя планирование, проверку результатов, извлечение данных и ожидание. В документации описаны классы агентов для конкретных платформ, использующие одинаковые методы ИИ, разделение длинных запросов на этапы в соответствии с границами страниц или фаз, загрузка файлов по запросу с ограничением на указанный каталог fileChooserAllowedDir (явно не рекомендуется использовать корневой каталог проекта или домашний каталог), системный параметр aiActionContext для указания уровня экспертизы тестировщика, распространенные ошибки при поиске элементов интерфейса и руководство по устранению неполадок.

Целевой аудиторией являются разработчики и инженеры по тестированию, создающие тесты типа E2E для разных платформ и нуждающиеся в надежной автоматизации на основе естественного языка для веб-платформ, Android и iOS. Для работы инструмента требуются настроенные переменные окружения (включая учетные данные модели ИИ для Midscene) и инструменты соответствующих платформ, такие как Playwright, ADB или WebDriverAgent. Этот инструмент запускает скрипт клонирования и управляет выполнением тестов, но предназначен только для законных сценариев тестирования; также рекомендуется ограничивать каталоги загрузки файлов, чтобы избежать рисков.

Часто задаваемые вопросы

Какие платформы поддерживаются?

Веб-платформы через Playwright Chromium, Android — через ADB и scrcpy, а iOS — через WebDriverAgent. Для веб-платформ доступны как ctx.agent, так и ctx.page; для Android и iOS — только ctx.agent. Все три агента используют одинаковые методы ИИ.

Как написать шаг теста?

Необходимо передать текстовый запрос пользователя в виде естественного языка в основной API aiAct, вместо того чтобы разбивать его на вызовы aiTap, aiInput или aiAssert. AiAct также обрабатывает проверку результатов, извлечение данных и ожидание; устаревший метод aiAction следует заменить на aiAct.

Какие настройки требуются?

Необходимо склонировать шаблон с помощью предоставленного скрипта, установить зависимости и настроить файл .env (скопированный из .env.example) с необходимыми переменными, включая учетные данные модели ИИ для Midscene. Также требуется соответствующий набор инструментов для конкретной платформы (Playwright, ADB/scrcpy или WebDriverAgent).

Как обеспечивается безопасная загрузка файлов?

При загрузке файлов с помощью запроса aiAct указывается каталог fileChooserAllowedDir, соответствующий самому мелкому каталогу, содержащему необходимые файлы для теста. В документации явно указано, что не следует использовать корневой каталог проекта или домашний каталог.

Что делать, если один запрос включает несколько шагов?

Необходимо разделить его на отдельные вызовы aiAct в соответствии с границами страниц или фаз, чтобы ИИ не терял контекст в процессе выполнения, при этом все этапы в совокупности должны соответствовать первоначальному запросу. В руководстве по устранению неполадок приведены способы диагностики ошибок.

Все файлы

3 файла SKILL.md 7,0 КБ View scripts/clone-boilerplate.sh 1,2 КБ View references/troubleshooting.md 2,2 КБ View

Посмотреть на GitHub

Modules

ModuleRole
VitestTypeScript test framework. Provides describe/it/expect/hooks for test organization, assertions, and lifecycle.
MidsceneAI-driven UI automation. Interacts with UI elements via natural language — no fragile selectors. Core API: aiAct.

Supported platforms:

  • Web — WebTest (Playwright Chromium): ctx.agent + ctx.page
  • Android — AndroidTest (ADB + scrcpy): ctx.agent only
  • iOS — IOSTest (WebDriverAgent): ctx.agent only

Workflow

Step 1: Clone boilerplate & ensure project ready

bash scripts/clone-boilerplate.sh

The boilerplate at ~/.midscene/boilerplate/vitest-all-platforms-demo/ is the canonical reference for project structure, configs, platform context classes, and test conventions. Compare the current project against it. If anything is missing, ask the user which platform(s) they need (Web / Android / iOS), then fill in what's missing using the boilerplate as the target state. Only include files for the requested platform(s). Do NOT overwrite existing configs or files. Copy .env.example from the boilerplate as .env if it doesn't exist, and prompt the user to fill in the env vars.

Step 2: Read the Midscene Agent API section below before writing tests

It contains mandatory rules for using aiAct — the primary API for all UI operations. Do NOT skip this step.

Step 3: Create, update, or run tests

Use the boilerplate's e2e/ directory and src/context/ as reference for patterns and conventions. Before running tests, ensure dependencies are installed and .env is configured. When debugging failures, check troubleshooting.md.

Midscene Agent API

ctx.agent is a platform-specific agent instance. All methods return Promises.

  • Web: PlaywrightAgent from @midscene/web/playwright
  • Android: AndroidAgent from @midscene/android
  • iOS: IOSAgent from @midscene/ios

All three agents share the same AI methods below.

Mandatory Rule: Use aiAct for User-Described Steps

When the user describes a UI action or state confirmation in natural language, you MUST use aiAct to implement it. Do NOT decompose user instructions into aiTap/aiInput/aiAssert or other fine-grained APIs. Pass the user's intent directly to aiAct and let Midscene's AI handle the planning and execution.

// User says: "type iPhone in the search box and click search"// WRONG — manually decomposing into fine-grained APIsawait ctx.agent.aiInput('search box', { value: 'iPhone' });await ctx.agent.aiTap('search button');// CORRECT — pass intent directly to aiActawait ctx.agent.aiAct('type "iPhone" in the search box, then click the search button');

Assertions, data extraction, and waiting should also be done via aiAct — it handles all of these. Do NOT use aiAssert, aiQuery, aiWaitFor, aiTap, or aiInput separately.

aiAct(taskPrompt, opt?) — Primary API

aiAct is the primary API for all UI operations and state confirmations. It accepts natural language instructions and autonomously plans and executes multi-step interactions.

// UI operationsawait ctx.agent.aiAct('type "iPhone" in the search box, then click the search button');await ctx.agent.aiAct('hover over the user avatar in the top right');// State confirmations / assertions — also use aiActawait ctx.agent.aiAct('verify the page shows "Login successful"');await ctx.agent.aiAct('verify the error message is visible');

Prompt-driven File Uploads (Web only)

When an aiAct prompt asks Midscene to upload files, pass fileChooserAllowedDir explicitly. Use the smallest directory containing that test case's fixtures, and refer to files relative to it in the prompt. Do not use the project root or a home directory. Replace ./fixtures below with the fixture directory relative to the test process working directory.

await ctx.agent.aiAct(  'click the upload button and upload avatar.png',  { fileChooserAllowedDir: './fixtures' },);

Phase splitting: If the task prompt is too long or covers multiple distinct stages, split it into separate aiAct calls — one per phase. Each phase should be a self-contained logical step, and all phases combined must match the user's original intent.

// Incorrect — prompt spans multiple pages and too many steps, AI may lose context mid-wayawait ctx.agent.aiAct('click the settings button in the top nav, go to settings page, find personal info and click into it, change email to "[email protected]", change phone to "13800000000", click save, wait for success');// Correct — split by page/stage boundary, each phase stays within one logical contextawait ctx.agent.aiAct('click the settings button in the top nav, go to settings page, find personal info and click into it');await ctx.agent.aiAct('change email to "[email protected]", change phone to "13800000000", click save');await ctx.agent.aiAct('verify the save success message appears');

aiAction is deprecated. Use aiAct or ai instead.

Common Mistakes

  • Vague locators — 'button' is ambiguous; use 'the blue "Submit" button at the top of the page'
  • Deprecated aiAction — use aiAct instead
  • Ambiguous multi-element targets — specify row/position: 'the delete button in the first product row'

Agent Configuration — aiActionContext

aiActionContext is a system prompt string appended to all AI actions performed by the agent. Use it to define the AI's role and expertise.

// Set via agentOptions in setup()const ctx = WebTest.setup('https://example.com', {  agentOptions: {    aiActionContext: 'You are a Web UI testing expert.',  },});

Good examples:

  • 'You are a Web UI testing expert.'
  • 'You are an Android app testing expert who is familiar with Chinese UI.'

Bad examples:

  • 'Click the login button.' — specific actions belong in aiAct(), not aiActionContext
  • 'The page is in Chinese.' — this is page description, not a system prompt

How to Look Up More

  1. In node_modules/@midscene/web, node_modules/@midscene/android, and node_modules/@midscene/ios, find the type definitions for the agent classes
  2. If types are not enough, follow the source references in the .d.ts files to read the implementation code in node_modules
  3. Download https://midscenejs.com/llms.txt, then use grep to search for the API or concept you need (the file is large, do not read it in full)

Установить vitest-midscene-e2e

Скачайте файлы с навыками и извлеките их в папку .claude/skills/.

Скачать ZIP

Клонируйте репозиторий и скопируйте файлы навыка в свой проект.

git clone https://github.com/web-infra-dev/midscene-skills/blob/main/skills/vitest-midscene-e2e/SKILL.md # Copy SKILL.md to your .claude/skills/ directory

Копировать Копировать
Быстрая настройка: Скопируйте папку с навыком в .claude/skills/ — Claude автоматически обнаружит её и начнёт использовать.
Репозиторий web-infra-dev/midscene-skills

Похожие навыки

playwright-cli
Обновлено время 29 июня 2026 г.
frontend-testing-best-practices
Обновлено время 7 июля 2026 г.
Playwright Browser Automation
Обновлено время 29 июня 2026 г.
playwright-generate-test
Обновлено время 29 июня 2026 г.
OR