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
feat(expect): toHaveCSS with object notation (#38982)
Dmitry Gozman750fc9406c41
diff --git a/docs/src/actionability.md b/docs/src/actionability.mdindex 3510171e5c..cff339faff 100644--- a/docs/src/actionability.md+++ b/docs/src/actionability.md@@ -66,7 +66,7 @@ Playwright includes auto-retrying assertions that remove flakiness by waiting un| [`method: LocatorAssertions.toHaveAttribute`] | Element has a DOM attribute || [`method: LocatorAssertions.toHaveClass`] | Element has a class property || [`method: LocatorAssertions.toHaveCount`] | List has exact number of children |-| [`method: LocatorAssertions.toHaveCSS`] | Element has CSS property |+| [`method: LocatorAssertions.toHaveCSS#1`] | Element has CSS property || [`method: LocatorAssertions.toHaveId`] | Element has an ID || [`method: LocatorAssertions.toHaveJSProperty`] | Element has a JavaScript property || [`method: LocatorAssertions.toHaveText`] | Element matches text |diff --git a/docs/src/api/class-locatorassertions.md b/docs/src/api/class-locatorassertions.mdindex 4473a9a333..eb8147a636 100644--- a/docs/src/api/class-locatorassertions.md+++ b/docs/src/api/class-locatorassertions.md@@ -351,7 +351,7 @@ Expected count.* since: v1.20* langs: python-The opposite of [`method: LocatorAssertions.toHaveCSS`].+The opposite of [`method: LocatorAssertions.toHaveCSS#1`].### param: LocatorAssertions.NotToHaveCSS.name* since: v1.18@@ -1694,7 +1694,7 @@ Expected count.### option: LocatorAssertions.toHaveCount.timeout = %%-csharp-java-python-assertions-timeout-%%* since: v1.18-## async method: LocatorAssertions.toHaveCSS+## async method: LocatorAssertions.toHaveCSS#1* since: v1.20* langs:- alias-java: hasCSS@@ -1731,24 +1731,51 @@ var locator = Page.GetByRole(AriaRole.Button);await Expect(locator).ToHaveCSSAsync("display", "flex");```-### param: LocatorAssertions.toHaveCSS.name+### param: LocatorAssertions.toHaveCSS#1.name* since: v1.18- `name` <[string]>CSS property name.-### param: LocatorAssertions.toHaveCSS.value+### param: LocatorAssertions.toHaveCSS#1.value* since: v1.18- `value` <[string]|[RegExp]>CSS property value.-### option: LocatorAssertions.toHaveCSS.timeout = %%-js-assertions-timeout-%%+### option: LocatorAssertions.toHaveCSS#1.timeout = %%-js-assertions-timeout-%%* since: v1.18-### option: LocatorAssertions.toHaveCSS.timeout = %%-csharp-java-python-assertions-timeout-%%+### option: LocatorAssertions.toHaveCSS#1.timeout = %%-csharp-java-python-assertions-timeout-%%* since: v1.18++## async method: LocatorAssertions.toHaveCSS#2+* since: v1.58+* langs: js++Ensures the [Locator] resolves to an element with the given computed CSS properties. Only the listed properties are checked.++**Usage**++```js+const locator = page.getByRole('button');+await expect(locator).toHaveCSS({+ display: 'flex',+ backgroundColor: 'rgb(255, 0, 0)'+});+```++### param: LocatorAssertions.toHaveCSS#2.styles+* since: v1.58+- `styles` <[Object]>++CSS properties object. See [CSSStyleProperties](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleProperties) for available properties.++### option: LocatorAssertions.toHaveCSS#2.timeout = %%-js-assertions-timeout-%%+* since: v1.58++## async method: LocatorAssertions.toHaveId* since: v1.20* langs:diff --git a/docs/src/release-notes-js.md b/docs/src/release-notes-js.mdindex da1add5293..8ee02008a8 100644--- a/docs/src/release-notes-js.md+++ b/docs/src/release-notes-js.md@@ -3196,7 +3196,7 @@ List of all new assertions:- [`expect(locator).toHaveAttribute(name, value)`](./api/class-locatorassertions#locator-assertions-to-have-attribute)- [`expect(locator).toHaveClass(expected)`](./api/class-locatorassertions#locator-assertions-to-have-class)- [`expect(locator).toHaveCount(count)`](./api/class-locatorassertions#locator-assertions-to-have-count)-- [`expect(locator).toHaveCSS(name, value)`](./api/class-locatorassertions#locator-assertions-to-have-css)+- [`expect(locator).toHaveCSS(name, value)`](./api/class-locatorassertions#locator-assertions-to-have-css-1)- [`expect(locator).toHaveId(id)`](./api/class-locatorassertions#locator-assertions-to-have-id)- [`expect(locator).toHaveJSProperty(name, value)`](./api/class-locatorassertions#locator-assertions-to-have-js-property)- [`expect(locator).toHaveText(expected, options)`](./api/class-locatorassertions#locator-assertions-to-have-text)diff --git a/docs/src/test-assertions-csharp-java-python.md b/docs/src/test-assertions-csharp-java-python.mdindex 114de1624a..520a9419b8 100644--- a/docs/src/test-assertions-csharp-java-python.md+++ b/docs/src/test-assertions-csharp-java-python.md@@ -24,7 +24,7 @@ title: "Assertions"| [`method: LocatorAssertions.toHaveAttribute`] | Element has a DOM attribute || [`method: LocatorAssertions.toHaveClass`] | Element has a class property || [`method: LocatorAssertions.toHaveCount`] | List has exact number of children |-| [`method: LocatorAssertions.toHaveCSS`] | Element has CSS property |+| [`method: LocatorAssertions.toHaveCSS#1`] | Element has CSS property || [`method: LocatorAssertions.toHaveId`] | Element has an ID || [`method: LocatorAssertions.toHaveJSProperty`] | Element has a JavaScript property || [`method: LocatorAssertions.toHaveRole`] | Element has a specific [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles) |diff --git a/docs/src/test-assertions-js.md b/docs/src/test-assertions-js.mdindex c809dce782..7baca2e707 100644--- a/docs/src/test-assertions-js.md+++ b/docs/src/test-assertions-js.md@@ -46,7 +46,7 @@ Note that retrying assertions are async, so you must `await` them.| [await expect(locator).toHaveAttribute()](./api/class-locatorassertions.md#locator-assertions-to-have-attribute) | Element has a DOM attribute || [await expect(locator).toHaveClass()](./api/class-locatorassertions.md#locator-assertions-to-have-class) | Element has specified CSS class property || [await expect(locator).toHaveCount()](./api/class-locatorassertions.md#locator-assertions-to-have-count) | List has exact number of children |-| [await expect(locator).toHaveCSS()](./api/class-locatorassertions.md#locator-assertions-to-have-css) | Element has CSS property |+| [await expect(locator).toHaveCSS()](./api/class-locatorassertions.md#locator-assertions-to-have-css-1) | Element has CSS property || [await expect(locator).toHaveId()](./api/class-locatorassertions.md#locator-assertions-to-have-id) | Element has an ID || [await expect(locator).toHaveJSProperty()](./api/class-locatorassertions.md#locator-assertions-to-have-js-property) | Element has a JavaScript property || [await expect(locator).toHaveRole()](./api/class-locatorassertions.md#locator-assertions-to-have-role) | Element has a specific [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles) |diff --git a/packages/injected/src/injectedScript.ts b/packages/injected/src/injectedScript.tsindex c0ac914bb2..1f45866bf5 100644--- a/packages/injected/src/injectedScript.ts+++ b/packages/injected/src/injectedScript.ts@@ -1423,7 +1423,7 @@ export class InjectedScript {// Element state / boolean values.let result: ElementStateQueryResult | undefined;if (expression === 'to.have.attribute') {- const hasAttribute = element.hasAttribute(options.expressionArg);+ const hasAttribute = element.hasAttribute(options.expressionArg || '');result = {matches: hasAttribute,received: hasAttribute ? 'attribute present' : 'attribute not present',@@ -1487,7 +1487,7 @@ export class InjectedScript {// JS propertyif (expression === 'to.have.property') {let target = element;- const properties = options.expressionArg.split('.');+ const properties = (options.expressionArg || '').split('.');for (let i = 0; i < properties.length - 1; i++) {if (typeof target !== 'object' || !(properties[i] in target))return { received: undefined, matches: false };@@ -1498,6 +1498,26 @@ export class InjectedScript {return { received, matches };}}++ {+ // Computed style object+ if (expression === 'to.have.css.object') {+ const expected = (options.expectedValue ?? {}) as Record<string, string>;+ const received: Record<string, string> = {};+ let matches = true;+ const style = this.window.getComputedStyle(element);+ for (const [prop, value] of Object.entries(expected)) {+ let computed = style[prop as any];+ if (typeof computed !== 'string')+ computed = '';+ if (computed !== value)+ matches = false;+ received[prop] = computed;+ }+ return { received, matches };+ }+ }+{// Viewport intersectionif (expression === 'to.be.in.viewport') {@@ -1534,7 +1554,7 @@ export class InjectedScript {// Single text value.let received: string | undefined;if (expression === 'to.have.attribute.value') {- const value = element.getAttribute(options.expressionArg);+ const value = element.getAttribute(options.expressionArg || '');if (value === null)return { received: null, matches: false };received = value;@@ -1546,7 +1566,7 @@ export class InjectedScript {matches: new ExpectedTextMatcher(options.expectedText[0]).matchesClassList(this, element.classList, /* partial */ expression === 'to.contain.class'),};} else if (expression === 'to.have.css') {- received = this.window.getComputedStyle(element).getPropertyValue(options.expressionArg);+ received = this.window.getComputedStyle(element).getPropertyValue(options.expressionArg || '');} else if (expression === 'to.have.id') {received = element.id;} else if (expression === 'to.have.text') {diff --git a/packages/playwright-core/src/protocol/validator.ts b/packages/playwright-core/src/protocol/validator.tsindex ea14d13902..a0f2bee782 100644--- a/packages/playwright-core/src/protocol/validator.ts+++ b/packages/playwright-core/src/protocol/validator.ts@@ -1921,7 +1921,7 @@ scheme.FrameWaitForSelectorResult = tObject({scheme.FrameExpectParams = tObject({selector: tOptional(tString),expression: tString,- expressionArg: tOptional(tAny),+ expressionArg: tOptional(tString),expectedText: tOptional(tArray(tType('ExpectedTextValue'))),expectedNumber: tOptional(tFloat),expectedValue: tOptional(tType('SerializedArgument')),diff --git a/packages/playwright-core/src/server/frames.ts b/packages/playwright-core/src/server/frames.tsindex a09b41d050..b32396d002 100644--- a/packages/playwright-core/src/server/frames.ts+++ b/packages/playwright-core/src/server/frames.ts@@ -1480,8 +1480,11 @@ export class Frame extends SdkObject<FrameEventMap> {lastIntermediateResult.received = received;}lastIntermediateResult.isSet = true;- if (!missingReceived && !Array.isArray(received))- progress.log(` unexpected value "${renderUnexpectedValue(options.expression, received)}"`);+ if (!missingReceived) {+ const rendered = renderUnexpectedValue(options.expression, received);+ if (rendered !== undefined)+ progress.log(` unexpected value "${rendered}"`);+ }}return { matches, received };}@@ -1745,8 +1748,10 @@ function verifyLifecycle(name: string, waitUntil: types.LifecycleEvent): types.Lreturn waitUntil;}-function renderUnexpectedValue(expression: string, received: any): string {+function renderUnexpectedValue(expression: string, received: any): string | undefined {if (expression === 'to.match.aria')- return received ? received.raw : received;- return received;+ received = received?.raw;+ if (Array.isArray(received) || (!!received && typeof received === 'object'))+ return;+ return String(received);}diff --git a/packages/playwright/src/matchers/matchers.ts b/packages/playwright/src/matchers/matchers.tsindex 08321af0c4..f1f1e784a4 100644--- a/packages/playwright/src/matchers/matchers.ts+++ b/packages/playwright/src/matchers/matchers.ts@@ -313,18 +313,30 @@ export function toHaveCount(}, expected, options);}+type ToHaveCSSOptions = { timeout?: number };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: Record<string, string>, options?: { timeout?: number }): Promise<MatcherResult<any, any>>;export function toHaveCSS(this: ExpectMatcherStateInternal,locator: LocatorEx,- name: string,- expected: string | RegExp,- options?: { timeout?: number },+ arg1: string | Record<string, string>,+ arg2?: string | RegExp | ToHaveCSSOptions,+ arg3?: ToHaveCSSOptions,) {- return toMatchText.call(this, 'toHaveCSS', locator, 'Locator', async (isNot, timeout) => {- const expectedText = serializeExpectedTextValues([expected]);- return await locator._expect('to.have.css', { expressionArg: name, expectedText, isNot, timeout });- }, expected, options);+ if (typeof arg1 === 'string') {+ if (arg2 === undefined || !(isString(arg2) || isRegExp(arg2)))+ throw new Error(`toHaveCSS expected value must be a string or a regular expression`);+ return toMatchText.call(this, 'toHaveCSS', locator, 'Locator', async (isNot, timeout) => {+ const expectedText = serializeExpectedTextValues([arg2]);+ return await locator._expect('to.have.css', { expressionArg: arg1, expectedText, isNot, timeout });+ }, arg2, arg3);+ } else {+ if (typeof arg1 !== 'object' || !arg1)+ throw new Error(`toHaveCSS argument must be a string or an object`);+ return toEqual.call(this, 'toHaveCSS', locator, 'Locator', async (isNot, timeout) => {+ return await locator._expect('to.have.css.object', { isNot, expectedValue: arg1, timeout });+ }, arg1, arg2 as (ToHaveCSSOptions | undefined));+ }}export function toHaveId(diff --git a/packages/playwright/types/test.d.ts b/packages/playwright/types/test.d.tsindex 9ed18fdf0e..011941effe 100644--- a/packages/playwright/types/test.d.ts+++ b/packages/playwright/types/test.d.ts@@ -8396,221 +8396,60 @@ type FunctionAssertions = {toPass(options?: { timeout?: number, intervals?: number[] }): Promise<void>;};-type BaseMatchers<R, T> = GenericAssertions<R> & PlaywrightTest.Matchers<R, T> & SnapshotAssertions;-type AllowedGenericMatchers<R, T> = PlaywrightTest.Matchers<R, T> & Pick<GenericAssertions<R>, 'toBe' | 'toBeDefined' | 'toBeFalsy' | 'toBeNull' | 'toBeTruthy' | 'toBeUndefined'>;--type SpecificMatchers<R, T> =- T extends Page ? PageAssertions & AllowedGenericMatchers<R, T> :- T extends Locator ? LocatorAssertions & AllowedGenericMatchers<R, T> :- T extends APIResponse ? APIResponseAssertions & AllowedGenericMatchers<R, T> :- BaseMatchers<R, T> & (T extends Function ? FunctionAssertions : {});-type AllMatchers<R, T> = PageAssertions & LocatorAssertions & APIResponseAssertions & FunctionAssertions & BaseMatchers<R, T>;--type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N;-type Awaited<T> = T extends PromiseLike<infer U> ? U : T;-type ToUserMatcher<F, DefaultReturnType> = F extends (first: any, ...args: infer Rest) => infer R ? (...args: Rest) => (R extends PromiseLike<infer U> ? Promise<void> : DefaultReturnType) : never;-type ToUserMatcherObject<T, DefaultReturnType, ArgType> = {- [K in keyof T as T[K] extends (arg: ArgType, ...rest: any[]) => any ? K : never]: ToUserMatcher<T[K], DefaultReturnType>;-};--type MatcherHintColor = (arg: string) => string;--export type MatcherHintOptions = {- comment?: string;- expectedColor?: MatcherHintColor;- isDirectExpectCall?: boolean;- isNot?: boolean;- promise?: string;- receivedColor?: MatcherHintColor;- secondArgument?: string;- secondArgumentColor?: MatcherHintColor;-};--export interface ExpectMatcherUtils {- matcherHint(matcherName: string, received: unknown, expected: unknown, options?: MatcherHintOptions): string;- printDiffOrStringify(expected: unknown, received: unknown, expectedLabel: string, receivedLabel: string, expand: boolean): string;- printExpected(value: unknown): string;- printReceived(object: unknown): string;- printWithType<T>(name: string, value: T, print: (value: T) => string): string;- diff(a: unknown, b: unknown): string | null;- stringify(object: unknown, maxDepth?: number, maxWidth?: number): string;-}--export type ExpectMatcherState = {- /**- * Whether this matcher was called with the negated .not modifier.- */- isNot: boolean;- /**- * - 'rejects' if matcher was called with the promise .rejects modifier- * - 'resolves' if matcher was called with the promise .resolves modifier- * - '' if matcher was not called with a promise modifier- */- promise: 'rejects' | 'resolves' | '';- utils: ExpectMatcherUtils;- /**- * Timeout in milliseconds for the assertion to be fulfilled.- */- timeout: number;-};--export type MatcherReturnType = {- message: () => string;- pass: boolean;- name?: string;- expected?: unknown;- actual?: any;- log?: string[];- timeout?: number;-};--type MakeMatchers<R, T, ExtendedMatchers> = {- /**- * If you know how to test something, `.not` lets you test its opposite.- */- not: MakeMatchers<R, T, ExtendedMatchers>;- /**- * Use resolves to unwrap the value of a fulfilled promise so any other- * matcher can be chained. If the promise is rejected the assertion fails.- */- resolves: MakeMatchers<Promise<R>, Awaited<T>, ExtendedMatchers>;- /**- * Unwraps the reason of a rejected promise so any other matcher can be chained.- * If the promise is fulfilled the assertion fails.- */- rejects: MakeMatchers<Promise<R>, any, ExtendedMatchers>;-} & IfAny<T, AllMatchers<R, T>, SpecificMatchers<R, T> & ToUserMatcherObject<ExtendedMatchers, R, T>>;--type PollMatchers<R, T, ExtendedMatchers> = {- /**- * If you know how to test something, `.not` lets you test its opposite.- */- not: PollMatchers<R, T, ExtendedMatchers>;-} & BaseMatchers<R, T> & ToUserMatcherObject<ExtendedMatchers, R, T>;--export type Expect<ExtendedMatchers = {}> = {- <T = unknown>(actual: T, messageOrOptions?: string | { message?: string }): MakeMatchers<void, T, ExtendedMatchers>;- soft: <T = unknown>(actual: T, messageOrOptions?: string | { message?: string }) => MakeMatchers<void, T, ExtendedMatchers>;- poll: <T = unknown>(actual: () => T | Promise<T>, messageOrOptions?: string | { message?: string, timeout?: number, intervals?: number[] }) => PollMatchers<Promise<void>, T, ExtendedMatchers>;- extend<MoreMatchers extends Record<string, (this: ExpectMatcherState, receiver: any, ...args: any[]) => MatcherReturnType | Promise<MatcherReturnType>>>(matchers: MoreMatchers): Expect<ExtendedMatchers & MoreMatchers>;- configure: (configuration: {- message?: string,- timeout?: number,- soft?: boolean,- }) => Expect<ExtendedMatchers>;- getState(): unknown;- not: Omit<AsymmetricMatchers, 'any' | 'anything'>;-} & AsymmetricMatchers;--// --- BEGINGLOBAL ----declare global {- export namespace PlaywrightTest {- export interface Matchers<R, T = unknown> {- }- }-}-// --- ENDGLOBAL -----/**- * These tests are executed in Playwright environment that launches the browser- * and provides a fresh page to each test.- */-export const test: TestType<PlaywrightTestArgs & PlaywrightTestOptions, PlaywrightWorkerArgs & PlaywrightWorkerOptions>;-export default test;--export const _baseTest: TestType<{}, {}>;-export const expect: Expect<{}>;--/**- * Defines Playwright config- */-export function defineConfig(config: PlaywrightTestConfig): PlaywrightTestConfig;-export function defineConfig<T>(config: PlaywrightTestConfig<T>): PlaywrightTestConfig<T>;-export function defineConfig<T, W>(config: PlaywrightTestConfig<T, W>): PlaywrightTestConfig<T, W>;-export function defineConfig(config: PlaywrightTestConfig, ...configs: PlaywrightTestConfig[]): PlaywrightTestConfig;-export function defineConfig<T>(config: PlaywrightTestConfig<T>, ...configs: PlaywrightTestConfig<T>[]): PlaywrightTestConfig<T>;-export function defineConfig<T, W>(config: PlaywrightTestConfig<T, W>, ...configs: PlaywrightTestConfig<T, W>[]): PlaywrightTestConfig<T, W>;--type MergedT<List> = List extends [TestType<infer T, any>, ...(infer Rest)] ? T & MergedT<Rest> : {};-type MergedW<List> = List extends [TestType<any, infer W>, ...(infer Rest)] ? W & MergedW<Rest> : {};-type MergedTestType<List> = TestType<MergedT<List>, MergedW<List>>;--/**- * Merges fixtures- */-export function mergeTests<List extends any[]>(...tests: List): MergedTestType<List>;--type MergedExpectMatchers<List> = List extends [Expect<infer M>, ...(infer Rest)] ? M & MergedExpectMatchers<Rest> : {};-type MergedExpect<List> = Expect<MergedExpectMatchers<List>>;+type CSSStyleProperties = { [k in Exclude<keyof CSSStyleDeclaration, 'parentRule' | number>]?: CSSStyleDeclaration[k] extends Function ? never : CSSStyleDeclaration[k] };/**- * Merges expects- */-export function mergeExpects<List extends any[]>(...expects: List): MergedExpect<List>;--// This is required to not export everything by default. See https://github.com/Microsoft/TypeScript/issues/19545#issuecomment-340490459-export { };----/**- * The [APIResponseAssertions](https://playwright.dev/docs/api/class-apiresponseassertions) class provides assertion- * methods that can be used to make assertions about the- * [APIResponse](https://playwright.dev/docs/api/class-apiresponse) in the tests.+ * The [LocatorAssertions](https://playwright.dev/docs/api/class-locatorassertions) class provides assertion methods+ * that can be used to make assertions about the [Locator](https://playwright.dev/docs/api/class-locator) state in the+ * tests.** ```js* import { test, expect } from '@playwright/test';*- * test('navigates to login', async ({ page }) => {+ * test('status becomes submitted', async ({ page }) => {* // ...- * const response = await page.request.get('https://playwright.dev');- * await expect(response).toBeOK();+ * await page.getByRole('button').click();+ * await expect(page.locator('.status')).toHaveText('Submitted');* });* ```**/-interface APIResponseAssertions {+interface LocatorAssertions {/**- * Ensures the response status code is within `200..299` range.+ * Ensures the [Locator](https://playwright.dev/docs/api/class-locator) resolves to an element with the given computed+ * CSS style.** **Usage**** ```js- * await expect(response).toBeOK();+ * const locator = page.getByRole('button');+ * await expect(locator).toHaveCSS('display', 'flex');* ```*+ * @param name CSS property name.+ * @param value CSS property value.+ * @param options*/- toBeOK(): Promise<void>;-+ toHaveCSS(name: string, value: string|RegExp, options?: { timeout?: number }): Promise<void>;/**- * Makes the assertion check for the opposite condition. For example, this code tests that the response status is not- * successful:+ * Ensures the [Locator](https://playwright.dev/docs/api/class-locator) resolves to an element with the given computed+ * CSS properties. Only the listed properties are checked.+ *+ * **Usage**** ```js- * await expect(response).not.toBeOK();+ * const locator = page.getByRole('button');+ * await expect(locator).toHaveCSS({+ * display: 'flex',+ * backgroundColor: 'rgb(255, 0, 0)'+ * });* ```*+ * @param styles CSS properties object. See+ * [CSSStyleProperties](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleProperties) for available properties.+ * @param options*/- not: APIResponseAssertions;-}--/**- * The [LocatorAssertions](https://playwright.dev/docs/api/class-locatorassertions) class provides assertion methods- * that can be used to make assertions about the [Locator](https://playwright.dev/docs/api/class-locator) state in the- * tests.- *- * ```js- * import { test, expect } from '@playwright/test';- *- * test('status becomes submitted', async ({ page }) => {- * // ...- * await page.getByRole('button').click();- * await expect(page.locator('.status')).toHaveText('Submitted');- * });- * ```- *- */-interface LocatorAssertions {+ toHaveCSS(values: CSSStyleProperties, options?: { timeout?: number }): Promise<void>;/*** Ensures that [Locator](https://playwright.dev/docs/api/class-locator) points to an element that is* [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.@@ -9163,28 +9002,6 @@ interface LocatorAssertions {timeout?: number;}): Promise<void>;- /**- * Ensures the [Locator](https://playwright.dev/docs/api/class-locator) resolves to an element with the given computed- * CSS style.- *- * **Usage**- *- * ```js- * const locator = page.getByRole('button');- * await expect(locator).toHaveCSS('display', 'flex');- * ```- *- * @param name CSS property name.- * @param value CSS property value.- * @param options- */- toHaveCSS(name: string, value: string|RegExp, options?: {- /**- * Time to retry the assertion for in milliseconds. Defaults to `timeout` in `TestConfig.expect`.- */- timeout?: number;- }): Promise<void>;-/*** Ensures the [Locator](https://playwright.dev/docs/api/class-locator) points to an element with the given DOM Node* ID.@@ -9626,6 +9443,204 @@ interface LocatorAssertions {not: LocatorAssertions;}+type BaseMatchers<R, T> = GenericAssertions<R> & PlaywrightTest.Matchers<R, T> & SnapshotAssertions;+type AllowedGenericMatchers<R, T> = PlaywrightTest.Matchers<R, T> & Pick<GenericAssertions<R>, 'toBe' | 'toBeDefined' | 'toBeFalsy' | 'toBeNull' | 'toBeTruthy' | 'toBeUndefined'>;++type SpecificMatchers<R, T> =+ T extends Page ? PageAssertions & AllowedGenericMatchers<R, T> :+ T extends Locator ? LocatorAssertions & AllowedGenericMatchers<R, T> :+ T extends APIResponse ? APIResponseAssertions & AllowedGenericMatchers<R, T> :+ BaseMatchers<R, T> & (T extends Function ? FunctionAssertions : {});+type AllMatchers<R, T> = PageAssertions & LocatorAssertions & APIResponseAssertions & FunctionAssertions & BaseMatchers<R, T>;++type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N;+type Awaited<T> = T extends PromiseLike<infer U> ? U : T;+type ToUserMatcher<F, DefaultReturnType> = F extends (first: any, ...args: infer Rest) => infer R ? (...args: Rest) => (R extends PromiseLike<infer U> ? Promise<void> : DefaultReturnType) : never;+type ToUserMatcherObject<T, DefaultReturnType, ArgType> = {+ [K in keyof T as T[K] extends (arg: ArgType, ...rest: any[]) => any ? K : never]: ToUserMatcher<T[K], DefaultReturnType>;+};++type MatcherHintColor = (arg: string) => string;++export type MatcherHintOptions = {+ comment?: string;+ expectedColor?: MatcherHintColor;+ isDirectExpectCall?: boolean;+ isNot?: boolean;+ promise?: string;+ receivedColor?: MatcherHintColor;+ secondArgument?: string;+ secondArgumentColor?: MatcherHintColor;+};++export interface ExpectMatcherUtils {+ matcherHint(matcherName: string, received: unknown, expected: unknown, options?: MatcherHintOptions): string;+ printDiffOrStringify(expected: unknown, received: unknown, expectedLabel: string, receivedLabel: string, expand: boolean): string;+ printExpected(value: unknown): string;+ printReceived(object: unknown): string;+ printWithType<T>(name: string, value: T, print: (value: T) => string): string;+ diff(a: unknown, b: unknown): string | null;+ stringify(object: unknown, maxDepth?: number, maxWidth?: number): string;+}++export type ExpectMatcherState = {+ /**+ * Whether this matcher was called with the negated .not modifier.+ */+ isNot: boolean;+ /**+ * - 'rejects' if matcher was called with the promise .rejects modifier+ * - 'resolves' if matcher was called with the promise .resolves modifier+ * - '' if matcher was not called with a promise modifier+ */+ promise: 'rejects' | 'resolves' | '';+ utils: ExpectMatcherUtils;+ /**+ * Timeout in milliseconds for the assertion to be fulfilled.+ */+ timeout: number;+};++export type MatcherReturnType = {+ message: () => string;+ pass: boolean;+ name?: string;+ expected?: unknown;+ actual?: any;+ log?: string[];+ timeout?: number;+};++type MakeMatchers<R, T, ExtendedMatchers> = {+ /**+ * If you know how to test something, `.not` lets you test its opposite.+ */+ not: MakeMatchers<R, T, ExtendedMatchers>;+ /**+ * Use resolves to unwrap the value of a fulfilled promise so any other+ * matcher can be chained. If the promise is rejected the assertion fails.+ */+ resolves: MakeMatchers<Promise<R>, Awaited<T>, ExtendedMatchers>;+ /**+ * Unwraps the reason of a rejected promise so any other matcher can be chained.+ * If the promise is fulfilled the assertion fails.+ */+ rejects: MakeMatchers<Promise<R>, any, ExtendedMatchers>;+} & IfAny<T, AllMatchers<R, T>, SpecificMatchers<R, T> & ToUserMatcherObject<ExtendedMatchers, R, T>>;++type PollMatchers<R, T, ExtendedMatchers> = {+ /**+ * If you know how to test something, `.not` lets you test its opposite.+ */+ not: PollMatchers<R, T, ExtendedMatchers>;+} & BaseMatchers<R, T> & ToUserMatcherObject<ExtendedMatchers, R, T>;++export type Expect<ExtendedMatchers = {}> = {+ <T = unknown>(actual: T, messageOrOptions?: string | { message?: string }): MakeMatchers<void, T, ExtendedMatchers>;+ soft: <T = unknown>(actual: T, messageOrOptions?: string | { message?: string }) => MakeMatchers<void, T, ExtendedMatchers>;+ poll: <T = unknown>(actual: () => T | Promise<T>, messageOrOptions?: string | { message?: string, timeout?: number, intervals?: number[] }) => PollMatchers<Promise<void>, T, ExtendedMatchers>;+ extend<MoreMatchers extends Record<string, (this: ExpectMatcherState, receiver: any, ...args: any[]) => MatcherReturnType | Promise<MatcherReturnType>>>(matchers: MoreMatchers): Expect<ExtendedMatchers & MoreMatchers>;+ configure: (configuration: {+ message?: string,+ timeout?: number,+ soft?: boolean,+ }) => Expect<ExtendedMatchers>;+ getState(): unknown;+ not: Omit<AsymmetricMatchers, 'any' | 'anything'>;+} & AsymmetricMatchers;++// --- BEGINGLOBAL ---+declare global {+ export namespace PlaywrightTest {+ export interface Matchers<R, T = unknown> {+ }+ }+}+// --- ENDGLOBAL ---++/**+ * These tests are executed in Playwright environment that launches the browser+ * and provides a fresh page to each test.+ */+export const test: TestType<PlaywrightTestArgs & PlaywrightTestOptions, PlaywrightWorkerArgs & PlaywrightWorkerOptions>;+export default test;++export const _baseTest: TestType<{}, {}>;+export const expect: Expect<{}>;++/**+ * Defines Playwright config+ */+export function defineConfig(config: PlaywrightTestConfig): PlaywrightTestConfig;+export function defineConfig<T>(config: PlaywrightTestConfig<T>): PlaywrightTestConfig<T>;+export function defineConfig<T, W>(config: PlaywrightTestConfig<T, W>): PlaywrightTestConfig<T, W>;+export function defineConfig(config: PlaywrightTestConfig, ...configs: PlaywrightTestConfig[]): PlaywrightTestConfig;+export function defineConfig<T>(config: PlaywrightTestConfig<T>, ...configs: PlaywrightTestConfig<T>[]): PlaywrightTestConfig<T>;+export function defineConfig<T, W>(config: PlaywrightTestConfig<T, W>, ...configs: PlaywrightTestConfig<T, W>[]): PlaywrightTestConfig<T, W>;++type MergedT<List> = List extends [TestType<infer T, any>, ...(infer Rest)] ? T & MergedT<Rest> : {};+type MergedW<List> = List extends [TestType<any, infer W>, ...(infer Rest)] ? W & MergedW<Rest> : {};+type MergedTestType<List> = TestType<MergedT<List>, MergedW<List>>;++/**+ * Merges fixtures+ */+export function mergeTests<List extends any[]>(...tests: List): MergedTestType<List>;++type MergedExpectMatchers<List> = List extends [Expect<infer M>, ...(infer Rest)] ? M & MergedExpectMatchers<Rest> : {};+type MergedExpect<List> = Expect<MergedExpectMatchers<List>>;++/**+ * Merges expects+ */+export function mergeExpects<List extends any[]>(...expects: List): MergedExpect<List>;++// This is required to not export everything by default. See https://github.com/Microsoft/TypeScript/issues/19545#issuecomment-340490459+export { };++++/**+ * The [APIResponseAssertions](https://playwright.dev/docs/api/class-apiresponseassertions) class provides assertion+ * methods that can be used to make assertions about the+ * [APIResponse](https://playwright.dev/docs/api/class-apiresponse) in the tests.+ *+ * ```js+ * import { test, expect } from '@playwright/test';+ *+ * test('navigates to login', async ({ page }) => {+ * // ...+ * const response = await page.request.get('https://playwright.dev');+ * await expect(response).toBeOK();+ * });+ * ```+ *+ */+interface APIResponseAssertions {+ /**+ * Ensures the response status code is within `200..299` range.+ *+ * **Usage**+ *+ * ```js+ * await expect(response).toBeOK();+ * ```+ *+ */+ toBeOK(): Promise<void>;++ /**+ * Makes the assertion check for the opposite condition. For example, this code tests that the response status is not+ * successful:+ *+ * ```js+ * await expect(response).not.toBeOK();+ * ```+ *+ */+ not: APIResponseAssertions;+}+/*** The [PageAssertions](https://playwright.dev/docs/api/class-pageassertions) class provides assertion methods that* can be used to make assertions about the [Page](https://playwright.dev/docs/api/class-page) state in the tests.diff --git a/packages/protocol/src/channels.d.ts b/packages/protocol/src/channels.d.tsindex 9944fb2aa9..406072af18 100644--- a/packages/protocol/src/channels.d.ts+++ b/packages/protocol/src/channels.d.ts@@ -3317,7 +3317,7 @@ export type FrameWaitForSelectorResult = {export type FrameExpectParams = {selector?: string,expression: string,- expressionArg?: any,+ expressionArg?: string,expectedText?: ExpectedTextValue[],expectedNumber?: number,expectedValue?: SerializedArgument,@@ -3327,7 +3327,7 @@ export type FrameExpectParams = {};export type FrameExpectOptions = {selector?: string,- expressionArg?: any,+ expressionArg?: string,expectedText?: ExpectedTextValue[],expectedNumber?: number,expectedValue?: SerializedArgument,diff --git a/packages/protocol/src/protocol.yml b/packages/protocol/src/protocol.ymlindex 4b19f911c9..b202cd7d2a 100644--- a/packages/protocol/src/protocol.yml+++ b/packages/protocol/src/protocol.yml@@ -2794,7 +2794,7 @@ Frame:parameters:selector: string?expression: string- expressionArg: json?+ expressionArg: string?expectedText:type: array?items: ExpectedTextValuediff --git a/tests/page/expect-misc.spec.ts b/tests/page/expect-misc.spec.tsindex 16901c8be0..c5615c8514 100644--- a/tests/page/expect-misc.spec.ts+++ b/tests/page/expect-misc.spec.ts@@ -518,6 +518,57 @@ test.describe('toHaveCSS', () => {const locator = page.locator('#node');await expect(locator).toHaveCSS('--custom-color-property', '#FF00FF');});++ test('fail with bad arguments', async ({ page }) => {+ await page.setContent(`<div id=node>hi</div>`);+ const locator = page.locator('#node');+ try {+ await expect(locator).toHaveCSS('property', {} as any);+ expect(true, 'should throw!').toBe(false);+ } catch (error) {+ expect(error.message).toContain(`toHaveCSS expected value must be a string or a regular expression`);+ }+ try {+ await expect(locator).toHaveCSS(123 as any, '123');+ expect(true, 'should throw!').toBe(false);+ } catch (error) {+ expect(error.message).toContain(`toHaveCSS argument must be a string or an object`);+ }+ });++ test('pass with object', async ({ page }) => {+ await page.setContent(`<div id=node style="color: rgb(255, 0, 0); display: flex; background-color: red;">Text content</div>`);+ const locator = page.locator('#node');+ await expect(locator).toHaveCSS({+ color: 'rgb(255, 0, 0)',+ display: 'flex',+ backgroundColor: 'rgb(255, 0, 0)',+ });+ });++ test('does not support custom properties inside object', async ({ page }) => {+ await page.setContent(`<div id=node style="--my-color: blue">Text content</div>`);+ const locator = page.locator('#node');+ await expect(locator).toHaveCSS({ '--my-color': '' } as any);+ });++ test('fail with object', async ({ page }) => {+ await page.setContent(`<div id=node style="color: rgb(255, 0, 0); display: flex; background-color: red;">Text content</div>`);+ const locator = page.locator('#node');+ const error = await expect(locator).toHaveCSS({+ 'color': 'blue',+ 'display': 'flex',+ 'backgroundColor': 'rgb(255, 0, 0)',+ }, { timeout: 3000 }).catch(e => e);+ expect(stripAnsi(error.message)).toContain(`+ Object {+ "backgroundColor": "rgb(255, 0, 0)",+- "color": "blue",++ "color": "rgb(255, 0, 0)",+ "display": "flex",+ }`);+ expect(stripAnsi(error.message)).not.toContain(`unexpected value "[object Object]"`);+ });});test.describe('toHaveId', () => {diff --git a/utils/generate_types/overrides-test.d.ts b/utils/generate_types/overrides-test.d.tsindex e71d6ebbf7..bfcac9586a 100644--- a/utils/generate_types/overrides-test.d.ts+++ b/utils/generate_types/overrides-test.d.ts@@ -400,6 +400,13 @@ type FunctionAssertions = {toPass(options?: { timeout?: number, intervals?: number[] }): Promise<void>;};+type CSSStyleProperties = { [k in Exclude<keyof CSSStyleDeclaration, 'parentRule' | number>]?: CSSStyleDeclaration[k] extends Function ? never : CSSStyleDeclaration[k] };++interface LocatorAssertions {+ toHaveCSS(name: string, value: string|RegExp, options?: { timeout?: number }): Promise<void>;+ toHaveCSS(values: CSSStyleProperties, options?: { timeout?: number }): Promise<void>;+}+type BaseMatchers<R, T> = GenericAssertions<R> & PlaywrightTest.Matchers<R, T> & SnapshotAssertions;type AllowedGenericMatchers<R, T> = PlaywrightTest.Matchers<R, T> & Pick<GenericAssertions<R>, 'toBe' | 'toBeDefined' | 'toBeFalsy' | 'toBeNull' | 'toBeTruthy' | 'toBeUndefined'>;