Skip to content

Commit eac236d

Browse files
authored
docs: explain how to type generic custom matchers (#43808)
1 parent f0f066e commit eac236d

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

‎docs/src/test-assertions-js.md‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,46 @@ test('amount', async () => {
343343
});
344344
```
345345
346+
### Generic custom matchers
347+
348+
TypeScript cannot carry a type parameter from the matcher implementation to the call site. If the matcher is generic over the received value, its type parameter becomes `unknown` when you call the matcher on `expect`.
349+
350+
To get the type of the received value in the matcher arguments, declare the matcher signature in the `PlaywrightTest.Matchers` interface. Its second type parameter `T` is the type of the value passed to `expect`. Note that a generic matcher also needs an explicit `this` parameter type to access `this.utils` and other matcher state.
351+
352+
```js title="fixtures.ts"
353+
import { expect as baseExpect } from '@playwright/test';
354+
import type { ExpectMatcherState } from '@playwright/test';
355+
356+
export const expect = baseExpect.extend({
357+
toSatisfy<T>(this: ExpectMatcherState, received: T, predicate: (value: T) => boolean) {
358+
const pass = predicate(received);
359+
return {
360+
message: () => `expected ${this.utils.printReceived(received)} to satisfy the predicate`,
361+
pass,
362+
};
363+
},
364+
});
365+
366+
declare global {
367+
namespace PlaywrightTest {
368+
interface Matchers<R, T = unknown> {
369+
toSatisfy(predicate: (value: T) => boolean): R;
370+
}
371+
}
372+
}
373+
```
374+
375+
Now the `value` argument has the type of the received value.
376+
377+
```js title="example.spec.ts"
378+
import { test, expect } from './fixtures';
379+
380+
test('generic matcher', async () => {
381+
expect('hello').toSatisfy(value => value.startsWith('h'));
382+
expect(42).toSatisfy(value => value > 40);
383+
});
384+
```
385+
346386
### Compatibility with expect library
347387
348388
:::note

0 commit comments

Comments
 (0)