【问题标题】:How do I fix 'return' outside of function when running a Node.js application?运行 Node.js 应用程序时,如何修复函数之外的“返回”?
【发布时间】:2020-10-09 01:19:42
【问题描述】:

对于Jest 来说相对较新 - 并且刚刚在一个原始环境/项目中毫无问题地使用它取得了成功,昨天我决定在旧的 Node.js 环境 (10.15.x) 中试一试。

最初,它运行良好。然后我开始引入旧的 requires 依赖项,它立即开始失败:

 FAIL  modules/reviews/review.jest.js
  ● Test suite failed to run

    SyntaxError: /Users/darrin/src/tot/commons/index.js: 'return' outside of function (2:0)

      1 | 'use strict';
    > 2 | return (module.exports = {
        | ^
      3 |       accessControl: require('./modules/accessControl'),
      4 |       about: require('./modules/about'),
      5 |       api: require('./modules/api'),

      at Parser.raise (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:6325:17)
      at Parser.parseReturnStatement (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:10190:12)
      at Parser.parseStatementContent (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9877:21)
      at Parser.parseStatement (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9829:17)
      at Parser.parseBlockOrModuleBlockBody (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:10405:25)
      at Parser.parseBlockBody (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:10392:10)
      at Parser.parseTopLevel (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9758:10)
      at Parser.parse (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:11270:17)
      at parse (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:11306:38)
      at parser (node_modules/@babel/core/lib/transformation/normalize-file.js:170:34)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.111s

对我来说,全局级别的返回(在这些依赖项中)在 JavaScript 中并不是严格意义上的,但这是有道理的,这对我来说是个新闻。仍然......我无法更改这些库,那么如何解决这个错误以便我可以使用 Jest?

【问题讨论】:

  • 显示/Users/darrin/src/tot/commons/index.js的内容
  • 嗨@MedetTleukabiluly,正如您所期望的那样,在全球范围内会有回报。我正在寻找一种方法来允许这种事情......

标签: javascript node.js unit-testing testing jestjs


【解决方案1】:

显然,我们对等待人们“修复”在全局范围内返回的库没有任何兴趣,因此使用 Jest 意味着我需要一种方法来忽略这些。

这是我最终做的:

  1. 在文件 package.json 中添加“jest”配置:

      "jest": {
        "transform": {
          "^.+\\.js$": "<rootDir>/.jest.transform.js"
        }
      },
    
  2. 然后在项目的根目录中创建文件 .jest.transform.js 并放置这个位告诉 Jest 告诉 Babel 允许在函数之外返回:

    const babelOptions = {
        parserOpts: {
            'allowReturnOutsideFunction': true
        },
    };
    module.exports = require('babel-jest').createTransformer(babelOptions);
    

我希望这对其他人有所帮助 - 因为这个细微差别,我几乎再次离开了 Jest!

【讨论】:

    猜你喜欢
    • 2021-10-11
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2014-10-28
    • 2021-01-27
    • 1970-01-01
    • 2018-06-09
    相关资源
    最近更新 更多