CodeSampleX

Пример

@playwright/test 1.49.0: expect.toContainText

Проверенный пример — npm @playwright/test 1.49.0: expect.toContainText. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:3b54e17a34761606a028a59e1456ba89dd54f81f1d55ca180ac6995103d9643e

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-21

Кейс

HOW
Цель
verify expect.toContainText in pkg:npm/%40playwright/test@1.49.0
Пакеты
Символы
  • expect.toContainText
Окружение
node 22.23.2
Создан
2026-08-21T10:40:50Z

Контракт

  1. expect.toContainText asserts locator text contains expected substring
  2. expect.toContainText supports regular expression pattern matching
  3. expect.toContainText supports case-insensitive matching with ignoreCase option
  4. expect.toContainText supports verifying arrays of expected text items across elements
  5. expect.toContainText supports negation via expect.not.toContainText for non-matching text

Файлы

  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify expect.toContainText in pkg:npm/%40playwright/test@1.49.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40playwright/test@1.49.0
Demonstrate these symbols/APIs:
  - expect.toContainText
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:7c25f53e6abefbe8558ffaa5d0abe9e236512bac69ab41c67ec803410920d4cf","constraints":{"executionContext":"node"},"contract":["expect.toContainText asserts locator text contains expected substring","expect.toContainText supports regular expression pattern matching","expect.toContainText supports case-insensitive matching with ignoreCase option","expect.toContainText supports verifying arrays of expected text items across elements","expect.toContainText supports negation via expect.not.toContainText for non-matching text"],"goal":"verify expect.toContainText in pkg:npm/%40playwright/test@1.49.0","kind":"HOW","packages":["pkg:npm/%40playwright/test@1.49.0"],"schemaVersion":1,"symbols":["expect.toContainText"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40playwright/test@1.49.0"],"schemaVersion":1,"subject":"pkg:npm/%40playwright/test@1.49.0","symbols":["expect.toContainText"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { expect } from '@playwright/test';

/**
 * Asserts that the element located by the Playwright Locator contains the expected substring.
 *
 * @param {{ _expect: Function }} locator - Playwright Locator instance or compatible interface.
 * @param {string} text - Expected substring to be contained in the element's text content.
 * @param {object} [options] - Optional assertion options (timeout, useInnerText).
 * @returns {Promise<void>} Resolves when assertion succeeds.
 */
export async function assertContainsText(locator, text, options = {}) {
  await expect(locator).toContainText(text, options);
}

/**
 * Asserts that the element located by the Playwright Locator matches the expected RegExp pattern.
 *
 * @param {{ _expect: Function }} locator - Playwright Locator instance or compatible interface.
 * @param {RegExp} pattern - Regular expression pattern to match against the element's text content.
 * @param {object} [options] - Optional assertion options (timeout, useInnerText).
 * @returns {Promise<void>} Resolves when assertion succeeds.
 */
export async function assertContainsPattern(locator, pattern, options = {}) {
  await expect(locator).toContainText(pattern, options);
}

/**
 * Asserts that the element located by the Playwright Locator contains the expected text ignoring case.
 *
 * @param {{ _expect: Function }} locator - Playwright Locator instance or compatible interface.
 * @param {string} text - Expected text to find regardless of uppercase/lowercase casing.
 * @param {object} [options] - Optional assertion options.
 * @returns {Promise<void>} Resolves when assertion succeeds.
 */
export async function assertContainsTextIgnoreCase(locator, text, options = {}) {
  await expect(locator).toContainText(text, { ...options, ignoreCase: true });
}

/**
 * Asserts that elements located by the Playwright Locator contain an array of expected text values.
 *
 * @param {{ _expect: Function }} locator - Playwright Locator instance representing multiple elements.
 * @param {Array<string|RegExp>} expectedList - Array of expected substrings or patterns.
 * @param {object} [options] - Optional assertion options.
 * @returns {Promise<void>} Resolves when assertion succeeds.
 */
export async function assertContainsTextList(locator, expectedList, options = {}) {
  await expect(locator).toContainText(expectedList, options);
}

/**
 * Asserts that the element located by the Playwright Locator does NOT contain the unexpected text.
 *
 * @param {{ _expect: Function }} locator - Playwright Locator instance or compatible interface.
 * @param {string|RegExp} unexpected - Substring or pattern that should not appear in the element's text.
 * @param {object} [options] - Optional assertion options.
 * @returns {Promise<void>} Resolves when negation assertion succeeds.
 */
export async function assertNotContainsText(locator, unexpected, options = {}) {
  await expect(locator).not.toContainText(unexpected, options);
}

export { expect };
package-lock.json
{
  "name": "sample-playwright-expect-to-contain-text",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-playwright-expect-to-contain-text",
      "version": "1.0.0",
      "dependencies": {
        "@playwright/test": "1.49.0"
      }
    },
    "node_modules/@playwright/test": {
      "version": "1.49.0",
      "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.49.0.tgz",
      "integrity": "sha512-DMulbwQURa8rNIQrf94+jPJQ4FmOVdpE5ZppRNvWVjvhC+6sOeo28r8MgIpQRYouXRtt/FCCXU7zn20jnHR4Qw==",
      "license": "Apache-2.0",
      "dependencies": {
        "playwright": "1.49.0"
      },
      "bin": {
        "playwright": "cli.js"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/fsevents": {
      "version": "2.3.2",
      "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
      "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
      "hasInstallScript": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "darwin"
      ],
      "engines": {
        "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
      }
    },
    "node_modules/playwright": {
      "version": "1.49.0",
      "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.49.0.tgz",
      "integrity": "sha512-eKpmys0UFDnfNb3vfsf8Vx2LEOtflgRebl0Im2eQQnYMA4Aqd+Zw8bEOB+7ZKvN76901mRnqdsiOGKxzVTbi7A==",
      "license": "Apache-2.0",
      "dependencies": {
        "playwright-core": "1.49.0"
      },
      "bin": {
        "playwright": "cli.js"
      },
      "engines": {
        "node": ">=18"
      },
      "optionalDependencies": {
        "fsevents": "2.3.2"
      }
    },
    "node_modules/playwright-core": {
      "version": "1.49.0",
      "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.49.0.tgz",
      "integrity": "sha512-R+3KKTQF3npy5GTiKH/T+kdhoJfJojjHESR1YEWhYuEKRVfVaxH3+4+GvXE5xyCngCxhxnykk0Vlah9v8fs3jA==",
      "license": "Apache-2.0",
      "bin": {
        "playwright-core": "cli.js"
      },
      "engines": {
        "node": ">=18"
      }
    }
  }
}
package.json
{
  "name": "sample-playwright-expect-to-contain-text",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "@playwright/test": "1.49.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify expect.toContainText in pkg:npm/%40playwright/test@1.49.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40playwright/test@1.49.0"
  ],
  "symbols": [
    "expect.toContainText"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import {
  assertContainsText,
  assertContainsPattern,
  assertContainsTextIgnoreCase,
  assertContainsTextList,
  assertNotContainsText,
  expect
} from '../index.mjs';

// Verify expect and expect.toContainText are properly exported
assert.strictEqual(typeof expect, 'function');
assert.strictEqual(typeof expect.toContainText, 'function');

// Helper to create mock Locator matching Playwright's Locator interface contract for expect
function createMockLocator(textContent) {
  return new class Locator {
    constructor(content) {
      this._content = content;
      this.calls = [];
    }

    async _expect(customExpression, options = {}) {
      this.calls.push({ customExpression, options });
      const isArray = Array.isArray(this._content);

      if (isArray) {
        const texts = this._content;
        const expectedTexts = options.expectedText || [];
        const matches = expectedTexts.every(exp => {
          return texts.some(t => {
            if (exp.regexSource) {
              const re = new RegExp(exp.regexSource, exp.regexFlags);
              return re.test(t);
            }
            if (exp.ignoreCase) {
              return t.toLowerCase().includes((exp.string || '').toLowerCase());
            }
            return t.includes(exp.string || '');
          });
        });
        return { matches, received: texts, log: [] };
      }

      const received = this._content;
      const exp = options.expectedText?.[0];
      let matches = false;

      if (exp) {
        if (exp.regexSource) {
          const re = new RegExp(exp.regexSource, exp.regexFlags);
          matches = re.test(received);
        } else if (exp.ignoreCase) {
          matches = received.toLowerCase().includes((exp.string || '').toLowerCase());
        } else {
          matches = received.includes(exp.string || '');
        }
      }

      return { matches, received, log: [] };
    }
  }(textContent);
}

// 1. expect.toContainText asserts locator text contains expected substring
{
  const locator = createMockLocator('Welcome to Playwright testing dashboard');
  await assertContainsText(locator, 'Playwright');
  await expect(locator).toContainText('dashboard');

  assert.strictEqual(locator.calls.length, 2);
  assert.strictEqual(locator.calls[0].customExpression, 'to.have.text');
}

// 2. expect.toContainText supports regular expression pattern matching
{
  const locator = createMockLocator('Order #12345 confirmed successfully');
  await assertContainsPattern(locator, /#\d{5}/);
  await expect(locator).toContainText(/confirmed/i);

  assert.strictEqual(locator.calls.length, 2);
  assert.ok(locator.calls[0].options.expectedText[0].regexSource);
}

// 3. expect.toContainText supports case-insensitive matching with ignoreCase option
{
  const locator = createMockLocator('STATUS: COMPLETED');
  await assertContainsTextIgnoreCase(locator, 'status: completed');
  await expect(locator).toContainText('completed', { ignoreCase: true });

  assert.strictEqual(locator.calls.length, 2);
  assert.strictEqual(locator.calls[0].options.expectedText[0].ignoreCase, true);
}

// 4. expect.toContainText supports verifying arrays of expected text items across elements
{
  const listLocator = createMockLocator([
    'Item Alpha: in stock',
    'Item Beta: out of stock',
    'Item Gamma: pending'
  ]);
  await assertContainsTextList(listLocator, ['Alpha', 'Gamma']);
  await expect(listLocator).toContainText(['Beta']);

  assert.strictEqual(listLocator.calls.length, 2);
  assert.strictEqual(listLocator.calls[0].customExpression, 'to.contain.text.array');
}

// 5. expect.toContainText supports negation via expect.not.toContainText for non-matching text
{
  const locator = createMockLocator('All checks passed with zero errors');
  await assertNotContainsText(locator, 'failure');
  await expect(locator).not.toContainText('critical');

  assert.strictEqual(locator.calls.length, 2);
}

// 6. expect.toContainText provides asymmetric matcher for composite assertions
{
  const matcher = expect.toContainText('sample-text');
  assert.strictEqual(typeof matcher.asymmetricMatch, 'function');
}

console.log('Contract test passed.');

Исходный сидер

аноним