【问题标题】:SyntaxError when running a Jest test containing import of a CoffeeScript file运行包含导入 CoffeeScript 文件的 Jest 测试时出现 SyntaxError
【发布时间】:2017-01-30 20:57:29
【问题描述】:

我正在编写一个 Jest 集成测试来测试我的服务器。这是我的测试:

import { app, port } from '../server' // the other lines are not so important
...

运行jest 时会引发错误:

__tests__/graphql.test.js
  ● Test suite failed to run

    <project folder>/node_modules/papercut/lib/papercut.coffee:3
    {FileStore, S3Store, TestStore } = require('./store')
                                     ^
    SyntaxError: Unexpected token =

我在 Jest 测试中需要 server.js,此文件需要 upload.js,而此文件需要名为 papercut 的节点模块。问题是,它是用 CoffeeScript 编写的,而不是纯 JS。

一开始我有这个错误:Jest: cannot find module required inside module to be tested (relative path)。我将coffee 添加到我的package.jsonjest 配置中:

"jest": {
  "moduleFileExtensions": ["js", "json", "jsx", "node", "coffee"]
},

但现在我遇到了上面描述的错误。

我该如何处理?

【问题讨论】:

  • 也许可以看看question 的“第二次尝试”部分,因为它展示了如何在导入时编译咖啡

标签: javascript coffeescript jestjs


【解决方案1】:

您需要为 Jest 设置一个 preprocessor,因为它无法处理咖啡脚本。

这个问题已经before回答了,所以我不会详细说明。 es6“开箱即用”的原因是因为已经提供了 jest-babel,因为 es6 在大多数 React 代码库中都是事实。

【讨论】:

  • 我尝试实现自己的预处理器,现在我收到此错误:gist.github.com/serge1peshcoff/6823cba9f464ea7e3f920af2d895bb69。似乎这个包在 CoffeeScript 中使用了一些 ES6 语法或类似的东西。
  • 而且奇怪的是它不是自己编译的,剪纸的index.js需要coffee-script自己,就像这样:require('coffee-script'); module.exports = require('./lib/papercut');
【解决方案2】:

我最终通过做两件事来解决它:

  • 为咖啡文件添加预处理器(与其他问题一样)
  • "preprocessorIgnorePatterns": [] 添加到我的 Jest 配置中。如果您不明确告诉它您也想编译这些文件,Jest 会忽略 node_modules/ 中的 .coffee 文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2019-03-15
    • 2017-12-28
    • 2019-10-28
    相关资源
    最近更新 更多