如何解决Jest测试在功能之外抛出“返回”的问题?

时间:2019-09-04 13:26:45

标签: 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

对我来说,有一个新闻是,在Java脚本中,在全局范围内(在这些依赖项中)返回并不是严格可行的,但这是有道理的。仍然...我无法更改这些库,所以如何解决此错误,以便可以使用Jest?

1 个答案:

答案 0 :(得分:0)

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

这就是我最终要做的:

  1. 将“笑话”配置添加到package.json
  "jest": {
    "transform": {
      "^.+\\.js$": "<rootDir>/.jest.transform.js"
    }
  },
  1. 然后将其放置在我创建的项目.jest.transform.js的根目录中,并放置此位置以告诉玩笑,告诉babel允许在函数之外返回:
const babelOptions = {
    parserOpts: {
        'allowReturnOutsideFunction': true
    },
};
module.exports = require('babel-jest').createTransformer(babelOptions);

我希望这对其他人有帮助-由于这种细微差别,我几乎又离开了Jest!