Babel unexpected token import when running mocha tests

前端 未结 17 1532
Happy的楠姐
Happy的楠姐 2020-11-27 14:40

The solutions offered in other related questions, such as including the proper presets (es2015) in .babelrc, are already implemented in my project.

I have two projec

17条回答
  •  佛祖请我去吃肉
    2020-11-27 14:51

    It seems the only solution is to explicitly include:

    require('babel-core/register')({
      ignore: /node_modules/(?!ProjectB)/
    }); 
    

    in a test helper file, and pass that along to mocha in my test command:

    mocha --require ./test/testHelper.js...
    

    The final solution:

    Add registerBabel.js: a separate file whose job is to require babel-core/register...

    require('babel-core/register')({
      ignore: /node_modules/(?!ProjectB)/
    });
    

    Add an entry.js if your application also relies on babel-node. This acts as a wrapper for your es6 containing application.

    require('./registerBabel');
    require('./server'); // this file has some es6 imports
    

    You would then run your application with node entry

    For mocha testing, testHelper.js should require registerBabel.js as well to initialize babel support at run time.

    require('./registerBabel');
    

    And run your mocha tests with mocha --require ./testHelper.js '+(test)/**/*Spec.js'

    This will recursively test any file ending in "Spec.js" within "./test". Substitute the pattern with one matching the specs in your project.

提交回复
热议问题