【问题标题】:SyntaxError: Missing initializer in const declarationSyntaxError: const 声明中缺少初始化程序
【发布时间】:2019-12-01 04:31:56
【问题描述】:

我正在我的 react native expo 应用程序中使用 react-native-testing-library(我使用该库的第一步)编写一个简单的测试。但是我从react-native 代码库本身的某个地方收到了一个令人困惑的错误。要么我的代码有问题,要么react-native-testing-library npm 库有错误。

这是一个简单的笑话测试:

describe("AppTitle", () => {
  it("should display applicaton title", () => {
    const { getByText } = render(<AppTitle />);
    expect(getByText('App Name')).toBeTruthy();
  });
});

这里是简单的&lt;AppTitle /&gt; 组件(只是一个视图和一个文本)

export const AppTitle = () => {
  return (
    <View>
      <Text>App Name</Text>
    </View>
  );
};

但我在运行测试时收到此错误:

...../Utilities/warnOnce.js:15

const warnedKeys: {[string]: boolean} = {};
      ^^^^^^^^^^

SyntaxError: Missing initializer in const declaration

at ScriptTransformer.transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
at Object.<anonymous> (node_modules/react-native/Libraries/react-native/react-native-implementation.js:14:18)
...

这是一个简单直接的模板。来自 react-native + react-native-testing-library 的任何帮助将不胜感激。

  1. 反应:16.8.3
  2. react-native: 来自Expo 33
  3. jest-expo: "^33.0.2"
  4. react-native-testing-library": "1.7.0"

【问题讨论】:

  • 你是如何设置 TypeScript 编译的?似乎您的 TS 类型声明未转换,因此 JS 解释器假设 : 只是一个标签或类似的东西
  • @skyboyer 我用“expo init app_name”创建了这个项目。我没有弹出,我搞砸了任何设置。新的 expo cli 工具使用内置支持 typescript 的 babel7 构建应用程序。也许我应该在 babel.config.js 中进行一些预设...我不知道...
  • 您需要安装/设置 ts-jestbabel-jest 或检查它是否已配置 levelup.gitconnected.com/… 请注意 TS 对 Jest 和构建的支持是独立的,因此即使一个仍然可以工作可能配置错误
  • 感谢您的建议。我安装了 ts-jest 并配置了 jest.config。但是现在我得到这个错误:SyntaxError: Unexpected token )。看起来 .tsx 文件没有被转译。我继续调查

标签: react-native jestjs react-testing-library


【解决方案1】:

我解决了这个在 jest.config.js 文件中添加的“preset”:“react-native”

【讨论】:

  • 遗憾的是这对我没有帮助。我仍然陷入与上述相同的错误:(
  • 根据 Jest documentation,现在应该默认包含在 package.json 文件中
【解决方案2】:

我在我的项目中使用 expo。我有同样的问题。我忘了在 package.json 中添加“preset”:“jest-expo”。我添加然后问题解决了。

 "jest": { "preset": "jest-expo" },

【讨论】: