I was going through the documentation on how to create custom matcher in typescript.
Consider that, we have this custom matcher:
// playwright.config.ts
import { expect, PlaywrightTestConfig } from '@playwright/test';
expect.extend({
toBeWithinRange(received: number, floor: number, ceiling: number) {
const pass = received >= floor && received <= ceiling;
if (pass) {
return {
message: () => 'passed',
pass: true,
};
} else {
return {
message: () => 'failed',
pass: false,
};
}
},
});
const config: PlaywrightTestConfig = {};
export default config;
// global.d.ts
declare global {
namespace PlaywrightTest {
interface Matchers<R> {
toBeWithinRange(a: number, b: number): R;
}
}
}
How to specify the type of receiver argument in the declaration.
expect(1).toBeWithinRange(0,5); // typescript no error expect("i am string").toBeWithinRange(0,5); // typescript error as received value is string
This thread is trying to answer question "How can the type of receiver argument be specified in the declaration of a custom matcher in Playwright using TypeScript?"
Related Ask AI answer for "How do I declare a custom matcher with a specified receiver argument type in Playwright using TypeScript?".
To declare a custom matcher with a specified receiver argument type in Playwright using TypeScript, you'll need to follow a few steps.
First, create a global.d.ts
file in your repository if it doesn't already exist. Make sure this file is included in your tsconfig.json
via the include
or compilerOptions.typeRoots
option.
export {};
Next, declare a namespace called PlaywrightTest
within the global namespace.
declare global {
namespace PlaywrightTest {
// Custom matchers go here
}
}
Inside the PlaywrightTest
namespace, define an interface called Matchers<R, T>
to extend Playwright's existing matchers.
declare global {
namespace PlaywrightTest {
interface Matchers<R, T> {
// Custom matcher declarations go here
}
}
}
Finally, within this interface, declare your custom matcher by specifying its name and arguments along with their types.
declare global {
namespace PlaywrightTest {
interface Matchers<R, T> {
myCustomMatcher(arg1: string): R;
// Add more custom matchers if needed
}
}
}
By following these steps, you can specify the type of receiver argument for each custom matcher in Playwright using TypeScript. If you need more information or have any questions, feel free to ask.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].