Search code examples
reactjstestingautomated-testse2e-testingtestcafe

TestCafé + React JSX error (unexpected Token)


I am new to test café, and am seeing some errors in my React project. All tests seem to be fine, except whenever it hits JSX code in a helper method, it gives a SyntaxError.

SyntaxError: .../_helpers.js: Unexpected token (779:29)
  777 |
  778 | export const customLegend = (data) => {
> 779 |   if (isEmpty(data)) return (<div />);


SyntaxError: .../_helpers.js: Unexpected token (710:4)
  708 |   } = props || {};
  709 |   return (
> 710 |     <div
      |     ^
  711 |       transform={`translate(${x},${y})`}

I have not found a solution yet, and I'm hoping someone has some tips.

The docs mention adding:

"compilerOptions": {
  "jsx": "react"
}

to a tsconfig.json file, but I'm not using typescript. so that just seems wrong.


Solution

  • Ok, I worked out the issue. in case anyone else lands here.

    On a react site, you can return some JSX in a function. This is handy when you need some simple html code, and don't want to create an entire component for it (such as when passing in a custom reCharts tick). When using test Café, you can't do this. Instead, you need to make sure all the jsx is in its own class component.

    you CAN still do the above mentioned shortcut, but only if the function itself is inside a component.

    i.e. BAD (it's valid in react, but NOT with testCafé)

    // in the chart component, you may have a custom tick element
    <XAxis dataKey={label} tick={customizedAxisTick} />
    
    // which, can look like this:
    export const customizedAxisTick = (props) => {
      const {
        payload = {}
      } = props || {};
      return (
        <div>
          custom stuff using the passed payload
        </div>
      );
    };
    

    GOOD: Instead, just make it its own class component

    // reference the new component, instead of a function that returns the jsx.
    <XAxis dataKey={label} tick={<AxisTick />} />
    
    // i.e.
    class AxisTick extends React.Component {
      ...
    
      render () {
        <div>
          custom stuff using the passed payload
        </div>
      }
    }