Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

5.6 KB
Raw Blame
/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as z from 'zod';
import { escapeWithQuotes } from '@isomorphic/stringUtils';

import { defineTabTool } from './tool';
import { locatorSelector } from './tab';
import type * as playwright from '../../..';

const verifyElement = defineTabTool({
  capability: 'testing',
  schema: {
    name: 'browser_verify_element_visible',
    title: 'Verify element visible',
    description: 'Verify element is visible on the page',
    inputSchema: z.object({
      role: z.string().describe('ROLE of the element. Can be found in the snapshot like this: \`- {ROLE} "Accessible Name":\`'),
      accessibleName: z.string().describe('ACCESSIBLE_NAME of the element. Can be found in the snapshot like this: \`- role "{ACCESSIBLE_NAME}"\`'),
    }),
    type: 'assertion',
  },

  handle: async (tab, params, response) => {
    for (const frame of tab.page.frames()) {
      const locator = frame.getByRole(params.role as Parameters<playwright.Frame['getByRole']>[0], { name: params.accessibleName });
      if (await locator.count() > 0) {
        const resolved = await locator.normalize();
        response.addAction({ name: 'assertVisible', selector: locatorSelector(resolved) });
        response.addTextResult('Done');
        return;
      }
    }
    response.addError(`Element with role "${params.role}" and accessible name "${params.accessibleName}" not found`);
  },
});

const verifyText = defineTabTool({
  capability: 'testing',
  schema: {
    name: 'browser_verify_text_visible',
    title: 'Verify text visible',
    description: `Verify text is visible on the page. Prefer ${verifyElement.schema.name} if possible.`,
    inputSchema: z.object({
      text: z.string().describe('TEXT to verify. Can be found in the snapshot like this: \`- role "Accessible Name": {TEXT}\` or like this: \`- text: {TEXT}\`'),
    }),
    type: 'assertion',
  },

  handle: async (tab, params, response) => {
    for (const frame of tab.page.frames()) {
      const locator = frame.getByText(params.text).filter({ visible: true });
      if (await locator.count() > 0) {
        const resolved = await locator.normalize();
        response.addAction({ name: 'assertVisible', selector: locatorSelector(resolved) });
        response.addTextResult('Done');
        return;
      }
    }
    response.addError('Text not found');
  },
});

const verifyList = defineTabTool({
  capability: 'testing',
  schema: {
    name: 'browser_verify_list_visible',
    title: 'Verify list visible',
    description: 'Verify list is visible on the page',
    inputSchema: z.object({
      element: z.string().describe('Human-readable list description'),
      target: z.string().describe('Exact target element reference that points to the list'),
      items: z.array(z.string()).describe('Items to verify'),
    }),
    type: 'assertion',
  },

  handle: async (tab, params, response) => {
    const { locator } = await tab.targetLocator(params);
    const itemTexts: string[] = [];
    for (const item of params.items) {
      const itemLocator = locator.getByText(item);
      if (await itemLocator.count() === 0) {
        response.addError(`Item "${item}" not found`);
        return;
      }
      itemTexts.push((await itemLocator.textContent(tab.expectTimeoutOptions))!);
    }
    const ariaSnapshot = `- list:
${itemTexts.map(t => `  - listitem: ${escapeWithQuotes(t, '"')}`).join('\n')}`;
    response.addAction({ name: 'assertSnapshot', selector: 'body', ariaSnapshot });
    response.addTextResult('Done');
  },
});

const verifyValue = defineTabTool({
  capability: 'testing',
  schema: {
    name: 'browser_verify_value',
    title: 'Verify value',
    description: 'Verify element value',
    inputSchema: z.object({
      type: z.enum(['textbox', 'checkbox', 'radio', 'combobox', 'slider']).describe('Type of the element'),
      element: z.string().describe('Human-readable element description'),
      target: z.string().describe('Exact target element reference from the page snapshot'),
      value: z.string().describe('Value to verify. For checkbox, use "true" or "false".'),
    }),
    type: 'assertion',
  },

  handle: async (tab, params, response) => {
    const { locator, selector } = await tab.targetLocator(params);
    if (params.type === 'textbox' || params.type === 'slider' || params.type === 'combobox') {
      const value = await locator.inputValue(tab.expectTimeoutOptions);
      if (value !== params.value) {
        response.addError(`Expected value "${params.value}", but got "${value}"`);
        return;
      }
      response.addAction({ name: 'assertValue', selector, value: params.value });
    } else if (params.type === 'checkbox' || params.type === 'radio') {
      const value = await locator.isChecked(tab.expectTimeoutOptions);
      if (value !== (params.value === 'true')) {
        response.addError(`Expected value "${params.value}", but got "${value}"`);
        return;
      }
      response.addAction({ name: 'assertChecked', selector, checked: value });
    }
    response.addTextResult('Done');
  },
});

export default [
  verifyElement,
  verifyText,
  verifyList,
  verifyValue,
];