Search code examples
javascripteslintabstract-syntax-tree

Forbid using screen outside of it/test with eslint's 'no-restricted-syntax'


I'm back trying to get 'no-restricted-syntx to work'. I've not got Prevent screen.findByX without an await with eslint no-restricted-syntax? to work, but I have another scenario where I need it. I noticed we were getting some issue related to a similar issue, with the explanation here:

You shouldn't render outside of a test()/it() block. The JSDOM env is global (shared between tests) and the cleanup in the inner describe() is cleaning up the DOM.

I have this kinda code:

beforeEach(async() => {
  render(<MyLovelyComponent />);
  await waitForElementToBeRemoved(() => screen.getAllByText('dddd'));
});

And I've like to warn/error on that screen being used there.

My attempt at writing the 'no-restricted-syntax' selector, based off some stuff from How to forbid a specific named function with ESlint as well, looks like:

'no-restricted-syntax':[
  'error',
  {
    message: 'No screen outside of it',
    selector: `FunctionCall[name!="it"] MemberExpression[object.name="screen"]`
  },
],

Here is my current attempt:

https://astexplorer.net/#/gist/53f841902242b436121b51ab4673344f/320bfaf0ac537c90fd501a0a969c79c1bb23f838

But it doesn't seem to be working.

Where have I gone wrong?


Solution

  • While writing this, I ended up double checking the AST Explorer and came up with:

    'no-restricted-syntax':[
      'error',
      {
        message: 'No screen inside beforeEach',
        selector: `CallExpression[callee.name="beforeEach"] MemberExpression[object.name="screen"]`
      },
    ],
    

    I still haven't got a way to block in in other ways not involving beforeEach but it's a start!