Skip to content

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

fix(expect): throw unsupported error when using this.equals() in expect (#31723)

Max Schmitted6abf86c743
diff --git a/docs/src/test-assertions-js.md b/docs/src/test-assertions-js.md
index 4745659cf9..defbc3a293 100644
--- a/docs/src/test-assertions-js.md
+++ b/docs/src/test-assertions-js.md
@@ -308,6 +308,8 @@ test('amount', async () => {
});
```
+### Compatibility with expect library
+
:::note
Do not confuse Playwright's `expect` with the [`expect` library](https://jestjs.io/docs/expect). The latter is not fully integrated with Playwright test runner, so make sure to use Playwright's own `expect`.
:::
diff --git a/packages/playwright/src/matchers/expect.ts b/packages/playwright/src/matchers/expect.ts
index 9a010992da..3e49360eb7 100644
--- a/packages/playwright/src/matchers/expect.ts
+++ b/packages/playwright/src/matchers/expect.ts
@@ -138,6 +138,7 @@ function createExpect(info: ExpectMetaInfo) {
utils,
timeout: currentExpectTimeout()
};
+ (newThis as any).equals = throwUnsupportedExpectMatcherError;
return (matcher as any).call(newThis, ...args);
};
}
@@ -183,6 +184,10 @@ function createExpect(info: ExpectMetaInfo) {
return expectInstance;
}
+function throwUnsupportedExpectMatcherError() {
+ throw new Error('It looks like you are using custom expect matchers that are not compatible with Playwright. See https://aka.ms/playwright/expect-compatibility');
+}
+
expectLibrary.setState({ expand: false });
const customAsyncMatchers = {
diff --git a/tests/playwright-test/expect.spec.ts b/tests/playwright-test/expect.spec.ts
index 1393bdd3ff..63928e86fb 100644
--- a/tests/playwright-test/expect.spec.ts
+++ b/tests/playwright-test/expect.spec.ts
@@ -1039,3 +1039,27 @@ test('should expose timeout to custom matchers', async ({ runInlineTest, runTSC
expect(result.failed).toBe(0);
expect(result.passed).toBe(2);
});
+
+test('should throw error when using .equals()', async ({ runInlineTest }) => {
+ const result = await runInlineTest({
+ 'helper.ts': `
+ import { test as base, expect } from '@playwright/test';
+ expect.extend({
+ toBeWithinRange(received, floor, ceiling) {
+ this.equals(1, 2);
+ },
+ });
+ export const test = base;
+ `,
+ 'expect-test.spec.ts': `
+ import { test } from './helper';
+ test('numeric ranges', () => {
+ test.expect(() => {
+ test.expect(100).toBeWithinRange(90, 110);
+ }).toThrowError('It looks like you are using custom expect matchers that are not compatible with Playwright. See https://aka.ms/playwright/expect-compatibility');
+ });
+ `
+ });
+ expect(result.exitCode).toBe(0);
+ expect(result.passed).toBe(1);
+});