运行包含CoffeeScript文件导入的Jest测试时出现SyntaxError

SyntaxError when running a Jest test containing import of a CoffeeScript file

本文关键字:测试 SyntaxError Jest 包含 CoffeeScript 文件 导入 运行      更新时间:2023-09-26

我正在编写一个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:不能找到模块内需要测试的模块(相对路径)。我将coffee添加到package.jsonjest配置中,如下所示:

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

但是现在出现了上面描述的错误

我该如何处理?

您需要为Jest设置一个预处理器,因为它不能原生处理coffee脚本。

这个问题之前已经有人回答过了,所以我就不细说了。es6"开箱即用"的原因是,在大多数React代码库中,es6实际上已经提供了jest-babel。

我最终通过做两件事解决了这个问题:

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