Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore: prepare to reuse expect formatting logic (#38792)
Dmitry Gozmand2d699bbb340
diff --git a/packages/playwright-core/src/server/utils/expectUtils.ts b/packages/playwright-core/src/server/utils/expectUtils.tsindex 6d7a2a1e3d..3fac8db843 100644--- a/packages/playwright-core/src/server/utils/expectUtils.ts+++ b/packages/playwright-core/src/server/utils/expectUtils.ts@@ -18,6 +18,16 @@ import { isRegExp, isString } from '../../utils/isomorphic/rtti';import type { ExpectedTextValue } from '@protocol/channels';+export interface InternalMatcherUtils {+ printDiffOrStringify(expected: unknown, received: unknown, expectedLabel: string, receivedLabel: string, expand: boolean): string;+ printExpected(value: unknown): string;+ printReceived(object: unknown): string;+ DIM_COLOR(text: string): string;+ RECEIVED_COLOR(text: string): string;+ INVERTED_COLOR(text: string): string;+ EXPECTED_COLOR(text: string): string;+}+export function serializeExpectedTextValues(items: (string | RegExp)[], options: { matchSubstring?: boolean, normalizeWhiteSpace?: boolean, ignoreCase?: boolean } = {}): ExpectedTextValue[] {return items.map(i => ({string: isString(i) ? i : undefined,@@ -28,3 +38,109 @@ export function serializeExpectedTextValues(items: (string | RegExp)[], options:normalizeWhiteSpace: options.normalizeWhiteSpace,}));}++// #region+// Mirrored from https://github.com/facebook/jest/blob/f13abff8df9a0e1148baf3584bcde6d1b479edc7/packages/expect/src/print.ts with minor modifications.+/**+ * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.+ *+ * This source code is licensed under the MIT license found here+ * https://github.com/facebook/jest/blob/1547740bbc26400d69f4576bf35645163e942829/LICENSE+ */++// Format substring but do not enclose in double quote marks.+// The replacement is compatible with pretty-format package.+const printSubstring = (val: string): string => val.replace(/"|\\/g, '\\$&');++export const printReceivedStringContainExpectedSubstring = (+ utils: InternalMatcherUtils,+ received: string,+ start: number,+ length: number, // not end+): string =>+ utils.RECEIVED_COLOR(+ '"' ++ printSubstring(received.slice(0, start)) ++ utils.INVERTED_COLOR(printSubstring(received.slice(start, start + length))) ++ printSubstring(received.slice(start + length)) ++ '"',+ );++export const printReceivedStringContainExpectedResult = (+ utils: InternalMatcherUtils,+ received: string,+ result: RegExpExecArray | null,+): string =>+ result === null+ ? utils.printReceived(received)+ : printReceivedStringContainExpectedSubstring(+ utils,+ received,+ result.index,+ result[0].length,+ );++// #endregion++type MatcherMessageDetails = {+ promise?: '' | 'rejects' | 'resolves';+ isNot?: boolean;+ receiver?: string; // Assuming 'locator' when locator is provided, 'page' otherwise.+ matcherName: string;+ expectation: string;+ locator?: string;+ printedExpected?: string;+ printedReceived?: string;+ printedDiff?: string;+ timedOut?: boolean;+ timeout?: number;+ errorMessage?: string;+ log?: string[];+};++export function formatMatcherMessage(utils: InternalMatcherUtils, details: MatcherMessageDetails) {+ const receiver = details.receiver ?? (details.locator ? 'locator' : 'page');+ let message = utils.DIM_COLOR('expect(') + utils.RECEIVED_COLOR(receiver)+ + utils.DIM_COLOR(')' + (details.promise ? '.' + details.promise : '') + (details.isNot ? '.not' : '') + '.')+ + details.matcherName+ + utils.DIM_COLOR('(') + utils.EXPECTED_COLOR(details.expectation) + utils.DIM_COLOR(')')+ + ' failed\n\n';++ // Sometimes diff is actually expected + received. Turn it into two lines to+ // simplify alignment logic.+ const diffLines = details.printedDiff?.split('\n');+ if (diffLines?.length === 2) {+ details.printedExpected = diffLines[0];+ details.printedReceived = diffLines[1];+ details.printedDiff = undefined;+ }++ const align = !details.errorMessage && details.printedExpected?.startsWith('Expected:')+ && (!details.printedReceived || details.printedReceived.startsWith('Received:'));+ if (details.locator)+ message += `Locator: ${align ? ' ' : ''}${details.locator}\n`;+ if (details.printedExpected)+ message += details.printedExpected + '\n';+ if (details.printedReceived)+ message += details.printedReceived + '\n';+ if (details.timedOut && details.timeout)+ message += `Timeout: ${align ? ' ' : ''}${details.timeout}ms\n`;+ if (details.printedDiff)+ message += details.printedDiff + '\n';+ if (details.errorMessage) {+ message += details.errorMessage;+ if (!details.errorMessage.endsWith('\n'))+ message += '\n';+ }+ message += callLogText(utils, details.log);+ return message;+}++export const callLogText = (utils: InternalMatcherUtils, log: string[] | undefined) => {+ if (!log || !log.some(l => !!l))+ return '';+ return `+Call log:+${utils.DIM_COLOR(log.join('\n'))}+`;+};diff --git a/packages/playwright/bundles/expect/src/expectBundleImpl.ts b/packages/playwright/bundles/expect/src/expectBundleImpl.tsindex cf818e2651..49e8f0563a 100644--- a/packages/playwright/bundles/expect/src/expectBundleImpl.ts+++ b/packages/playwright/bundles/expect/src/expectBundleImpl.ts@@ -16,11 +16,3 @@import expectLibrary from 'expect';export const expect = expectLibrary;--export {- EXPECTED_COLOR,- INVERTED_COLOR,- RECEIVED_COLOR,- DIM_COLOR,- printReceived,-} from 'jest-matcher-utils';diff --git a/packages/playwright/src/common/expectBundle.ts b/packages/playwright/src/common/expectBundle.tsindex ebec808537..960c55adea 100644--- a/packages/playwright/src/common/expectBundle.ts+++ b/packages/playwright/src/common/expectBundle.ts@@ -15,8 +15,3 @@*/export const expect: typeof import('../../bundles/expect/node_modules/expect/build').expect = require('./expectBundleImpl').expect;-export const EXPECTED_COLOR: typeof import('../../bundles/expect/node_modules/jest-matcher-utils/build').EXPECTED_COLOR = require('./expectBundleImpl').EXPECTED_COLOR;-export const INVERTED_COLOR: typeof import('../../bundles/expect/node_modules/jest-matcher-utils/build').INVERTED_COLOR = require('./expectBundleImpl').INVERTED_COLOR;-export const RECEIVED_COLOR: typeof import('../../bundles/expect/node_modules/jest-matcher-utils/build').RECEIVED_COLOR = require('./expectBundleImpl').RECEIVED_COLOR;-export const DIM_COLOR: typeof import('../../bundles/expect/node_modules/jest-matcher-utils/build').DIM_COLOR = require('./expectBundleImpl').DIM_COLOR;-export const printReceived: typeof import('../../bundles/expect/node_modules/jest-matcher-utils/build').printReceived = require('./expectBundleImpl').printReceived;diff --git a/packages/playwright/src/matchers/expect.ts b/packages/playwright/src/matchers/expect.tsindex 248cebe5f5..02d2da2f0c 100644--- a/packages/playwright/src/matchers/expect.ts+++ b/packages/playwright/src/matchers/expect.ts@@ -58,10 +58,7 @@ import {import { toMatchAriaSnapshot } from './toMatchAriaSnapshot';import { toHaveScreenshot, toMatchSnapshot } from './toMatchSnapshot';import {- INVERTED_COLOR,- RECEIVED_COLOR,expect as expectLibrary,- printReceived,} from '../common/expectBundle';import { currentTestInfo } from '../common/globals';import { filteredStackTrace } from '../util';@@ -71,47 +68,6 @@ import type { ExpectMatcherStateInternal } from './matchers';import type { Expect } from '../../types/test';import type { TestStepInfoImpl } from '../worker/testInfo';--// #region-// Mirrored from https://github.com/facebook/jest/blob/f13abff8df9a0e1148baf3584bcde6d1b479edc7/packages/expect/src/print.ts-/**- * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.- *- * This source code is licensed under the MIT license found here- * https://github.com/facebook/jest/blob/1547740bbc26400d69f4576bf35645163e942829/LICENSE- */--// Format substring but do not enclose in double quote marks.-// The replacement is compatible with pretty-format package.-const printSubstring = (val: string): string => val.replace(/"|\\/g, '\\$&');--export const printReceivedStringContainExpectedSubstring = (- received: string,- start: number,- length: number, // not end-): string =>- RECEIVED_COLOR(- '"' +- printSubstring(received.slice(0, start)) +- INVERTED_COLOR(printSubstring(received.slice(start, start + length))) +- printSubstring(received.slice(start + length)) +- '"',- );--export const printReceivedStringContainExpectedResult = (- received: string,- result: RegExpExecArray | null,-): string =>- result === null- ? printReceived(received)- : printReceivedStringContainExpectedSubstring(- received,- result.index,- result[0].length,- );--// #endregion-type ExpectMessage = string | { message?: string };function createMatchers(actual: unknown, info: ExpectMetaInfo, prefix: string[]): any {@@ -447,7 +403,7 @@ async function pollMatcher(qualifiedMatcherName: string, info: ExpectMetaInfo, p}}-export const expect: Expect<{}> = createExpect({}, [], {}).extend(customMatchers);+export const expect: Expect<{}> = createExpect({}, [], {}).extend(customMatchers as any);export function mergeExpects(...expects: any[]) {let merged = expect;diff --git a/packages/playwright/src/matchers/matcherHint.ts b/packages/playwright/src/matchers/matcherHint.tsindex 7c0b809b35..bc7e846bab 100644--- a/packages/playwright/src/matchers/matcherHint.ts+++ b/packages/playwright/src/matchers/matcherHint.ts@@ -15,63 +15,8 @@*/import { stringifyStackFrames } from 'playwright-core/lib/utils';-import { DIM_COLOR, RECEIVED_COLOR, EXPECTED_COLOR } from '../common/expectBundle';-import type { ExpectMatcherState } from '../../types/test';import type { StackFrame } from '@protocol/channels';-import type { Locator } from 'playwright-core';--type MatcherMessageDetails = {- receiver?: string; // Assuming 'locator' when locator is provided, 'page' otherwise.- matcherName: string;- expectation: string;- locator?: Locator;- printedExpected?: string;- printedReceived?: string;- printedDiff?: string;- timedOut?: boolean;- timeout?: number;- errorMessage?: string;- log?: string[];-};--export function formatMatcherMessage(state: ExpectMatcherState, details: MatcherMessageDetails) {- const receiver = details.receiver ?? (details.locator ? 'locator' : 'page');- let message = DIM_COLOR('expect(') + RECEIVED_COLOR(receiver)- + DIM_COLOR(')' + (state.promise ? '.' + state.promise : '') + (state.isNot ? '.not' : '') + '.')- + details.matcherName- + DIM_COLOR('(') + EXPECTED_COLOR(details.expectation) + DIM_COLOR(')')- + ' failed\n\n';-- // Sometimes diff is actually expected + received. Turn it into two lines to- // simplify alignment logic.- const diffLines = details.printedDiff?.split('\n');- if (diffLines?.length === 2) {- details.printedExpected = diffLines[0];- details.printedReceived = diffLines[1];- details.printedDiff = undefined;- }-- const align = !details.errorMessage && details.printedExpected?.startsWith('Expected:')- && (!details.printedReceived || details.printedReceived.startsWith('Received:'));- if (details.locator)- message += `Locator: ${align ? ' ' : ''}${String(details.locator)}\n`;- if (details.printedExpected)- message += details.printedExpected + '\n';- if (details.printedReceived)- message += details.printedReceived + '\n';- if (details.timedOut && details.timeout)- message += `Timeout: ${align ? ' ' : ''}${details.timeout}ms\n`;- if (details.printedDiff)- message += details.printedDiff + '\n';- if (details.errorMessage) {- message += details.errorMessage;- if (!details.errorMessage.endsWith('\n'))- message += '\n';- }- message += callLogText(details.log);- return message;-}export type MatcherResult<E, A> = {name: string;@@ -111,12 +56,3 @@ export class ExpectError extends Error {export function isJestError(e: unknown): e is JestError {return e instanceof Error && 'matcherResult' in e && !!e.matcherResult;}--export const callLogText = (log: string[] | undefined) => {- if (!log || !log.some(l => !!l))- return '';- return `-Call log:-${DIM_COLOR(log.join('\n'))}-`;-};diff --git a/packages/playwright/src/matchers/matchers.ts b/packages/playwright/src/matchers/matchers.tsindex 03f8b9f4ac..dbde0329e8 100644--- a/packages/playwright/src/matchers/matchers.ts+++ b/packages/playwright/src/matchers/matchers.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { asLocatorDescription, constructURLBasedOnBaseURL, isRegExp, isString, isTextualMimeType, pollAgainstDeadline, serializeExpectedTextValues, toKebabCase } from 'playwright-core/lib/utils';+import { asLocatorDescription, constructURLBasedOnBaseURL, isRegExp, isString, isTextualMimeType, pollAgainstDeadline, serializeExpectedTextValues, toKebabCase, formatMatcherMessage } from 'playwright-core/lib/utils';import { colors } from 'playwright-core/lib/utils';import { expectTypes } from '../util';@@ -26,15 +26,19 @@ import { toHaveScreenshotStepTitle } from './toMatchSnapshot';import { takeFirst } from '../common/config';import { currentTestInfo } from '../common/globals';import { TestInfoImpl } from '../worker/testInfo';-import { formatMatcherMessage, MatcherResult } from './matcherHint';+import { MatcherResult } from './matcherHint';import type { ExpectMatcherState } from '../../types/test';import type { TestStepInfoImpl } from '../worker/testInfo';import type { APIResponse, Locator, Frame, Page } from 'playwright-core';import type { FrameExpectParams } from 'playwright-core/lib/client/types';-import type { CSSProperties } from '../../types/test';+import type { CSSProperties, ExpectMatcherUtils } from '../../types/test';+import type { InternalMatcherUtils } from 'playwright-core/lib/utils';-export type ExpectMatcherStateInternal = ExpectMatcherState & { _stepInfo?: TestStepInfoImpl };+export type ExpectMatcherStateInternal = Omit<ExpectMatcherState, 'utils'> & {+ _stepInfo?: TestStepInfoImpl;+ utils: ExpectMatcherUtils & InternalMatcherUtils;+};export interface LocatorEx extends Locator {_selector: string;@@ -50,7 +54,7 @@ interface APIResponseEx extends APIResponse {}export function toBeAttached(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,options?: { attached?: boolean, timeout?: number },) {@@ -63,7 +67,7 @@ export function toBeAttached(}export function toBeChecked(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,options?: { checked?: boolean, indeterminate?: boolean, timeout?: number },) {@@ -88,7 +92,7 @@ export function toBeChecked(}export function toBeDisabled(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,options?: { timeout?: number },) {@@ -98,7 +102,7 @@ export function toBeDisabled(}export function toBeEditable(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,options?: { editable?: boolean, timeout?: number },) {@@ -111,7 +115,7 @@ export function toBeEditable(}export function toBeEmpty(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,options?: { timeout?: number },) {@@ -121,7 +125,7 @@ export function toBeEmpty(}export function toBeEnabled(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,options?: { enabled?: boolean, timeout?: number },) {@@ -134,7 +138,7 @@ export function toBeEnabled(}export function toBeFocused(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,options?: { timeout?: number },) {@@ -144,7 +148,7 @@ export function toBeFocused(}export function toBeHidden(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,options?: { timeout?: number },) {@@ -154,7 +158,7 @@ export function toBeHidden(}export function toBeVisible(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,options?: { visible?: boolean, timeout?: number },) {@@ -167,7 +171,7 @@ export function toBeVisible(}export function toBeInViewport(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,options?: { timeout?: number, ratio?: number },) {@@ -177,7 +181,7 @@ export function toBeInViewport(}export function toContainText(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expected: string | RegExp | (string | RegExp)[],options: { timeout?: number, useInnerText?: boolean, ignoreCase?: boolean } = {},@@ -196,7 +200,7 @@ export function toContainText(}export function toHaveAccessibleDescription(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expected: string | RegExp,options?: { timeout?: number, ignoreCase?: boolean },@@ -208,7 +212,7 @@ export function toHaveAccessibleDescription(}export function toHaveAccessibleName(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expected: string | RegExp,options?: { timeout?: number, ignoreCase?: boolean },@@ -220,7 +224,7 @@ export function toHaveAccessibleName(}export function toHaveAccessibleErrorMessage(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expected: string | RegExp,options?: { timeout?: number; ignoreCase?: boolean },@@ -232,7 +236,7 @@ export function toHaveAccessibleErrorMessage(}export function toHaveAttribute(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,name: string,expected: string | RegExp | undefined | { timeout?: number },@@ -257,7 +261,7 @@ export function toHaveAttribute(}export function toHaveClass(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expected: string | RegExp | (string | RegExp)[],options?: { timeout?: number },@@ -276,7 +280,7 @@ export function toHaveClass(}export function toContainClass(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expected: string | string[],options?: { timeout?: number },@@ -299,7 +303,7 @@ export function toContainClass(}export function toHaveCount(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expected: number,options?: { timeout?: number },@@ -309,10 +313,10 @@ export function toHaveCount(}, expected, options);}-export function toHaveCSS(this: ExpectMatcherState, locator: LocatorEx, name: string, expected: string | RegExp, options?: { timeout?: number }): Promise<MatcherResult<any, any>>;-export function toHaveCSS(this: ExpectMatcherState, locator: LocatorEx, styles: CSSProperties, options?: { timeout?: number }): Promise<MatcherResult<any, any>>;+export function toHaveCSS(this: ExpectMatcherStateInternal, locator: LocatorEx, name: string, expected: string | RegExp, options?: { timeout?: number }): Promise<MatcherResult<any, any>>;+export function toHaveCSS(this: ExpectMatcherStateInternal, locator: LocatorEx, styles: CSSProperties, options?: { timeout?: number }): Promise<MatcherResult<any, any>>;export function toHaveCSS(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,nameOrStyles: string | CSSProperties,expectedOrOptions?: (string | RegExp) | { timeout?: number },@@ -347,7 +351,7 @@ export function toHaveCSS(}export function toHaveId(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expected: string | RegExp,options?: { timeout?: number },@@ -359,7 +363,7 @@ export function toHaveId(}export function toHaveJSProperty(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,name: string,expected: any,@@ -371,7 +375,7 @@ export function toHaveJSProperty(}export function toHaveRole(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expected: string,options?: { timeout?: number, ignoreCase?: boolean },@@ -385,7 +389,7 @@ export function toHaveRole(}export function toHaveText(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expected: string | RegExp | (string | RegExp)[],options: { timeout?: number, useInnerText?: boolean, ignoreCase?: boolean } = {},@@ -404,7 +408,7 @@ export function toHaveText(}export function toHaveValue(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expected: string | RegExp,options?: { timeout?: number },@@ -416,7 +420,7 @@ export function toHaveValue(}export function toHaveValues(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expected: (string | RegExp)[],options?: { timeout?: number },@@ -428,7 +432,7 @@ export function toHaveValues(}export function toHaveTitle(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,page: Page,expected: string | RegExp,options: { timeout?: number } = {},@@ -440,7 +444,7 @@ export function toHaveTitle(}export function toHaveURL(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,page: Page,expected: string | RegExp | ((url: URL) => boolean),options?: { ignoreCase?: boolean; timeout?: number },@@ -458,7 +462,7 @@ export function toHaveURL(}export async function toBeOK(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,response: APIResponseEx) {const matcherName = 'toBeOK';@@ -471,7 +475,9 @@ export async function toBeOK(isTextEncoding ? response.text() : null]) : [];- const message = () => formatMatcherMessage(this, {+ const message = () => formatMatcherMessage(this.utils, {+ isNot: this.isNot,+ promise: this.promise,matcherName,receiver: 'response',expectation: '',diff --git a/packages/playwright/src/matchers/toBeTruthy.ts b/packages/playwright/src/matchers/toBeTruthy.tsindex 0802277421..3f4dc9c71e 100644--- a/packages/playwright/src/matchers/toBeTruthy.ts+++ b/packages/playwright/src/matchers/toBeTruthy.ts@@ -14,15 +14,16 @@* limitations under the License.*/+import { formatMatcherMessage } from 'playwright-core/lib/utils';+import { expectTypes } from '../util';-import { formatMatcherMessage } from './matcherHint';import type { MatcherResult } from './matcherHint';-import type { ExpectMatcherState } from '../../types/test';import type { Locator } from 'playwright-core';+import type { ExpectMatcherStateInternal } from './matchers';export async function toBeTruthy(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,matcherName: string,locator: Locator,receiverType: string,@@ -56,10 +57,12 @@ export async function toBeTruthy(printedReceived = errorMessage ? '' : `Received: ${received}`;}const message = () => {- return formatMatcherMessage(this, {+ return formatMatcherMessage(this.utils, {+ isNot: this.isNot,+ promise: this.promise,matcherName,expectation: arg,- locator,+ locator: locator.toString(),timeout,timedOut,printedExpected,diff --git a/packages/playwright/src/matchers/toEqual.ts b/packages/playwright/src/matchers/toEqual.tsindex e22f8a9c65..e158f61802 100644--- a/packages/playwright/src/matchers/toEqual.ts+++ b/packages/playwright/src/matchers/toEqual.ts@@ -14,21 +14,20 @@* limitations under the License.*/-import { isRegExp } from 'playwright-core/lib/utils';+import { formatMatcherMessage, isRegExp } from 'playwright-core/lib/utils';import { expectTypes } from '../util';-import { formatMatcherMessage } from './matcherHint';import type { MatcherResult } from './matcherHint';-import type { ExpectMatcherState } from '../../types/test';import type { Locator } from 'playwright-core';+import type { ExpectMatcherStateInternal } from './matchers';// Omit colon and one or more spaces, so can call getLabelPrinter.const EXPECTED_LABEL = 'Expected';const RECEIVED_LABEL = 'Received';export async function toEqual<T>(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,matcherName: string,locator: Locator,receiverType: string,@@ -84,10 +83,12 @@ export async function toEqual<T>();}const message = () => {- return formatMatcherMessage(this, {+ return formatMatcherMessage(this.utils, {+ isNot: this.isNot,+ promise: this.promise,matcherName,expectation: 'expected',- locator,+ locator: locator.toString(),timeout,timedOut,printedExpected,diff --git a/packages/playwright/src/matchers/toHaveURL.ts b/packages/playwright/src/matchers/toHaveURL.tsindex f3c4ded541..959eca13c1 100644--- a/packages/playwright/src/matchers/toHaveURL.ts+++ b/packages/playwright/src/matchers/toHaveURL.ts@@ -14,18 +14,14 @@* limitations under the License.*/-import { urlMatches } from 'playwright-core/lib/utils';--import { printReceivedStringContainExpectedResult } from './expect';-import { formatMatcherMessage } from './matcherHint';-import { printReceived } from '../common/expectBundle';+import { formatMatcherMessage, printReceivedStringContainExpectedResult, urlMatches } from 'playwright-core/lib/utils';import type { MatcherResult } from './matcherHint';-import type { ExpectMatcherState } from '../../types/test';import type { Page } from 'playwright-core';+import type { ExpectMatcherStateInternal } from './matchers';export async function toHaveURLWithPredicate(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,page: Page,expected: (url: URL) => boolean,options?: { ignoreCase?: boolean; timeout?: number },@@ -85,7 +81,7 @@ export async function toHaveURLWithPredicate(}function toHaveURLMessage(- state: ExpectMatcherState,+ state: ExpectMatcherStateInternal,matcherName: string,expected: Function,received: string | undefined,@@ -100,11 +96,11 @@ function toHaveURLMessage(let printedDiff: string | undefined;if (typeof expected === 'function') {printedExpected = `Expected: predicate to ${!state.isNot ? 'succeed' : 'fail'}`;- printedReceived = `Received: ${printReceived(receivedString)}`;+ printedReceived = `Received: ${state.utils.printReceived(receivedString)}`;} else {if (pass) {printedExpected = `Expected pattern: not ${state.utils.printExpected(expected)}`;- const formattedReceived = printReceivedStringContainExpectedResult(receivedString, null);+ const formattedReceived = printReceivedStringContainExpectedResult(state.utils, receivedString, null);printedReceived = `Received string: ${formattedReceived}`;} else {const labelExpected = `Expected ${typeof expected === 'string' ? 'string' : 'pattern'}`;@@ -112,7 +108,9 @@ function toHaveURLMessage(}}- return formatMatcherMessage(state, {+ return formatMatcherMessage(state.utils, {+ isNot: state.isNot,+ promise: state.promise,matcherName,expectation: 'expected',timeout,diff --git a/packages/playwright/src/matchers/toMatchAriaSnapshot.ts b/packages/playwright/src/matchers/toMatchAriaSnapshot.tsindex 1075d8d86d..1f11d8ee3f 100644--- a/packages/playwright/src/matchers/toMatchAriaSnapshot.ts+++ b/packages/playwright/src/matchers/toMatchAriaSnapshot.ts@@ -18,16 +18,13 @@import fs from 'fs';import path from 'path';-import { escapeTemplateString, isString } from 'playwright-core/lib/utils';+import { formatMatcherMessage, escapeTemplateString, isString, printReceivedStringContainExpectedSubstring } from 'playwright-core/lib/utils';-import { formatMatcherMessage } from './matcherHint';import { fileExistsAsync } from '../util';-import { printReceivedStringContainExpectedSubstring } from './expect';import { currentTestInfo } from '../common/globals';import type { MatcherResult } from './matcherHint';-import type { LocatorEx } from './matchers';-import type { ExpectMatcherState } from '../../types/test';+import type { ExpectMatcherStateInternal, LocatorEx } from './matchers';import type { MatcherReceived } from '@injected/ariaSnapshot';@@ -38,7 +35,7 @@ type ToMatchAriaSnapshotExpected = {} | string;export async function toMatchAriaSnapshot(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,locator: LocatorEx,expectedParam?: ToMatchAriaSnapshotExpected,options: { timeout?: number } = {},@@ -93,16 +90,18 @@ export async function toMatchAriaSnapshot(if (errorMessage) {printedExpected = `Expected: ${this.isNot ? 'not ' : ''}${this.utils.printExpected(expected)}`;} else if (pass) {- const receivedString = printReceivedStringContainExpectedSubstring(typedReceived.raw, typedReceived.raw.indexOf(expected), expected.length);+ const receivedString = printReceivedStringContainExpectedSubstring(this.utils, typedReceived.raw, typedReceived.raw.indexOf(expected), expected.length);printedExpected = `Expected: not ${this.utils.printExpected(expected)}`;printedReceived = `Received: ${receivedString}`;} else {printedDiff = this.utils.printDiffOrStringify(expected, typedReceived.raw, 'Expected', 'Received', false);}- return formatMatcherMessage(this, {+ return formatMatcherMessage(this.utils, {+ isNot: this.isNot,+ promise: this.promise,matcherName,expectation: 'expected',- locator,+ locator: locator.toString(),timeout,timedOut,printedExpected,diff --git a/packages/playwright/src/matchers/toMatchSnapshot.ts b/packages/playwright/src/matchers/toMatchSnapshot.tsindex 3f36ea6445..661bf88d07 100644--- a/packages/playwright/src/matchers/toMatchSnapshot.ts+++ b/packages/playwright/src/matchers/toMatchSnapshot.ts@@ -17,12 +17,11 @@import fs from 'fs';import path from 'path';-import { compareBuffersOrStrings, getComparator, isString } from 'playwright-core/lib/utils';+import { callLogText, formatMatcherMessage, compareBuffersOrStrings, getComparator, isString } from 'playwright-core/lib/utils';import { colors } from 'playwright-core/lib/utils';import { mime } from 'playwright-core/lib/utilsBundle';import { addSuffixToFilePath, expectTypes } from '../util';-import { callLogText, formatMatcherMessage } from './matcherHint';import { currentTestInfo } from '../common/globals';import type { MatcherResult } from './matcherHint';@@ -82,8 +81,10 @@ class SnapshotHelper {readonly options: Omit<ToHaveScreenshotOptions, '_comparator'> & { comparator?: string };readonly matcherName: string;readonly locator: Locator | undefined;+ readonly state: ExpectMatcherStateInternal;constructor(+ state: ExpectMatcherStateInternal,testInfo: TestInfoImpl,matcherName: 'toMatchSnapshot' | 'toHaveScreenshot',locator: Locator | undefined,@@ -141,6 +142,7 @@ class SnapshotHelper {this.comparator = getComparator(this.mimeType);this.testInfo = testInfo;+ this.state = state;this.kind = this.mimeType.startsWith('image/') ? 'Screenshot' : 'Snapshot';}@@ -234,7 +236,7 @@ class SnapshotHelper {}if (log?.length)- output.push(callLogText(log));+ output.push(callLogText(this.state.utils, log));elseoutput.push('');@@ -263,7 +265,7 @@ export function toMatchSnapshot(const configOptions = testInfo._projectInternal.expect?.toMatchSnapshot || {};const helper = new SnapshotHelper(- testInfo, 'toMatchSnapshot', undefined, '.' + determineFileExtension(received),+ this, testInfo, 'toMatchSnapshot', undefined, '.' + determineFileExtension(received),configOptions, nameOrOptions, optOptions);if (this.isNot) {@@ -301,7 +303,7 @@ export function toMatchSnapshot(if (!result)return helper.handleMatching();- const header = formatMatcherMessage(this, { matcherName: 'toMatchSnapshot', receiver: isString(received) ? 'string' : 'Buffer', expectation: 'expected' });+ const header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toMatchSnapshot', receiver: isString(received) ? 'string' : 'Buffer', expectation: 'expected' });return helper.handleDifferent(received, expected, undefined, result.diff, header, result.errorMessage, undefined, this._stepInfo);}@@ -333,7 +335,7 @@ export async function toHaveScreenshot(expectTypes(pageOrLocator, ['Page', 'Locator'], 'toHaveScreenshot');const [page, locator] = pageOrLocator.constructor.name === 'Page' ? [(pageOrLocator as PageEx), undefined] : [(pageOrLocator as Locator).page() as PageEx, pageOrLocator as Locator];const configOptions = testInfo._projectInternal.expect?.toHaveScreenshot || {};- const helper = new SnapshotHelper(testInfo, 'toHaveScreenshot', locator, undefined, configOptions, nameOrOptions, optOptions);+ const helper = new SnapshotHelper(this, testInfo, 'toHaveScreenshot', locator, undefined, configOptions, nameOrOptions, optOptions);if (!helper.expectedPath.toLowerCase().endsWith('.png'))throw new Error(`Screenshot name "${path.basename(helper.expectedPath)}" must have '.png' extension`);expectTypes(pageOrLocator, ['Page', 'Locator'], 'toHaveScreenshot');@@ -381,7 +383,7 @@ export async function toHaveScreenshot(// We tried re-generating new snapshot but failed.// This can be due to e.g. spinning animation, so we want to show it as a diff.if (errorMessage) {- const header = formatMatcherMessage(this, { matcherName: 'toHaveScreenshot', locator, expectation: 'expected', timeout, timedOut });+ const header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });return helper.handleDifferent(actual, undefined, previous, diff, header, errorMessage, log, this._stepInfo);}@@ -416,12 +418,12 @@ export async function toHaveScreenshot(if (helper.updateSnapshots === 'changed' || helper.updateSnapshots === 'all') {if (actual)return writeFiles(actual);- let header = formatMatcherMessage(this, { matcherName: 'toHaveScreenshot', locator, expectation: 'expected', timeout, timedOut });+ let header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });header += ' Failed to re-generate expected.\n';return helper.handleDifferent(actual, expectScreenshotOptions.expected, previous, diff, header, errorMessage, log, this._stepInfo);}- const header = formatMatcherMessage(this, { matcherName: 'toHaveScreenshot', locator, expectation: 'expected', timeout, timedOut });+ const header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });return helper.handleDifferent(actual, expectScreenshotOptions.expected, previous, diff, header, errorMessage, log, this._stepInfo);}diff --git a/packages/playwright/src/matchers/toMatchText.ts b/packages/playwright/src/matchers/toMatchText.tsindex 508702bcd0..85410d734b 100644--- a/packages/playwright/src/matchers/toMatchText.ts+++ b/packages/playwright/src/matchers/toMatchText.ts@@ -14,21 +14,16 @@* limitations under the License.*/+import { formatMatcherMessage, printReceivedStringContainExpectedResult, printReceivedStringContainExpectedSubstring } from 'playwright-core/lib/utils';import { expectTypes } from '../util';-import {- printReceivedStringContainExpectedResult,- printReceivedStringContainExpectedSubstring-} from './expect';-import { formatMatcherMessage } from './matcherHint';-import { EXPECTED_COLOR } from '../common/expectBundle';import type { MatcherResult } from './matcherHint';-import type { ExpectMatcherState } from '../../types/test';import type { Page, Locator } from 'playwright-core';+import type { ExpectMatcherStateInternal } from './matchers';export async function toMatchText(- this: ExpectMatcherState,+ this: ExpectMatcherStateInternal,matcherName: string,receiver: Locator | Page,receiverType: 'Locator' | 'Page',@@ -43,8 +38,8 @@ export async function toMatchText(!(typeof expected === 'string') &&!(expected && typeof expected.test === 'function')) {- const errorMessage = `Error: ${EXPECTED_COLOR('expected')} value must be a string or regular expression\n${this.utils.printWithType('Expected', expected, this.utils.printExpected)}`;- throw new Error(formatMatcherMessage(this, { locator, matcherName, expectation: 'expected', errorMessage }));+ const errorMessage = `Error: ${this.utils.EXPECTED_COLOR('expected')} value must be a string or regular expression\n${this.utils.printWithType('Expected', expected, this.utils.printExpected)}`;+ throw new Error(formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, locator: locator?.toString(), matcherName, expectation: 'expected', errorMessage }));}const timeout = options.timeout ?? this.timeout;@@ -70,13 +65,13 @@ export async function toMatchText(if (typeof expected === 'string') {printedExpected = `Expected${expectedSuffix}: not ${this.utils.printExpected(expected)}`;if (!errorMessage) {- const formattedReceived = printReceivedStringContainExpectedSubstring(receivedString, receivedString.indexOf(expected), expected.length);+ const formattedReceived = printReceivedStringContainExpectedSubstring(this.utils, receivedString, receivedString.indexOf(expected), expected.length);printedReceived = `Received${receivedSuffix}: ${formattedReceived}`;}} else {printedExpected = `Expected${expectedSuffix}: not ${this.utils.printExpected(expected)}`;if (!errorMessage) {- const formattedReceived = printReceivedStringContainExpectedResult(receivedString, typeof expected.exec === 'function' ? expected.exec(receivedString) : null);+ const formattedReceived = printReceivedStringContainExpectedResult(this.utils, receivedString, typeof expected.exec === 'function' ? expected.exec(receivedString) : null);printedReceived = `Received${receivedSuffix}: ${formattedReceived}`;}}@@ -88,10 +83,12 @@ export async function toMatchText(}const message = () => {- return formatMatcherMessage(this, {+ return formatMatcherMessage(this.utils, {+ promise: this.promise,+ isNot: this.isNot,matcherName,expectation: 'expected',- locator,+ locator: locator?.toString(),timeout,timedOut,printedExpected,