javascript - 运行 Node.js 应用程序时,如何在函数外修复 'return'?

标签 javascript node.js unit-testing testing jestjs

相对较新 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?

最佳答案

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

这是我最后做的:

  1. 将“jest”配置添加到文件package.json:

      "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!

关于javascript - 运行 Node.js 应用程序时,如何在函数外修复 'return'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57789431/

相关文章:

dom - 使用 node.js 解析 html 页面的首选 DOM 库?

unit-testing - 如何在 Grails 单元测试中使用 Spock 模拟 passwordEncoder

unit-testing - NUnit 没有运行我的测试用例

javascript - 试图解码诈骗脚本的结果

javascript - 使用 jQuery 完全删除和替换 Div 内容

javascript - 一行推送item数组并返回item

c++ - 如何测试从 std::istream 读取类?

javascript - 通过 npm 安装 d3.js 对 Angular 2 TypeScript 项目有什么好处吗?

javascript - int 的奇怪属性

node.js - Mongodb 按今天的日期查找创建的结果