【问题标题】:TestCafé + React JSX error (unexpected Token)TestCafé + React JSX 错误(意外的令牌)
【发布时间】:2026-01-21 01:40:02
【问题描述】:

我是测试咖啡厅的新手,在我的 React 项目中发现了一些错误。所有测试似乎都很好,除非它在辅助方法中遇到 JSX 代码时,它会给出一个 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})`}

我还没有找到解决办法,希望有人能给点建议。

文档提到添加:

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

到 tsconfig.json 文件,但我没有使用打字稿。所以这似乎是错误的。

【问题讨论】:

    标签: reactjs testing automated-tests e2e-testing testcafe


    【解决方案1】:

    TestCafe 转译进程未配置为处理 JSX 文件。

    请参阅以下主题以查找更多信息:

    Testcafe wont recognise React

    【讨论】:

    • 是的,我看到了那个帖子,但它是从 2 年前开始的,所以我认为他们现在必须解决这个问题,考虑到反应的普遍性。还有 testcafe-react-selectors 插件,如果他们甚至不支持基于 JSX 的 react,我无法想象它会存在。
    【解决方案2】:

    好的,我解决了这个问题。以防其他人降落在这里。

    在反应站点上,您可以在函数中返回一些 JSX。当您需要一些简单的 html 代码并且不想为其创建整个组件时(例如传入自定义 reCharts 刻度时),这很方便。使用 test Café 时,您不能这样做。相反,您需要确保所有 jsx 都在其自己的类组件中。

    您仍然可以使用上述快捷方式,但前提是函数本身位于组件内部。

    即 BAD(在 react 中有效,但在 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>
      );
    };
    

    好的:相反,只需使其成为自己的类组件

    // 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>
      }
    }
    
    

    【讨论】:

      最近更新 更多