Home > OS >  typescript - How to enforce object destructuring in functions
typescript - How to enforce object destructuring in functions

Time:12-26

I am working with playwright e2e testing, and I noticed that when trying to use beforeEach as a function of my own without destructing the page from the args property

test.beforeEach((args, testInfo) => {
    console.log('heyo');
  });

i got the following error:

 npm run test

> [email protected] test
> playwright test

Error: First argument must use the object destructuring pattern: args
  defined at playwright/appName.test.ts:7:8

I want to have the same functionality in my functions (to enforce using destructuring) how can I achieve this?

I tried digging through the playwright code to understand how they did it without success.

CodePudding user response:

What playwright does is looking at the source code of the function at runtime, and doing some rudimentary parsing to check and enforce the destructing.

https://github.com/microsoft/playwright/blob/233664bd30c137159df02c1dd58f4e5391e9fa20/packages/playwright-test/src/fixtures.ts#L427-L443

The important bits:

// get me the code
const text = fn.toString();
// after naive parsing, check if we are destructing
  if (firstParam[0] !== '{' || firstParam[firstParam.length - 1] !== '}')
    addFatalError('First argument must use the object destructuring pattern: '    firstParam, location);

Do no attempt to do this, unless you have a solid reason to do so

  • Related