Jared Smith
Jared Smith

Reputation: 21936

Testing ES 2015 modules with Mocha

I was just assigned a project at work that uses raw native imports/exports (only supports the latest browsers), a large piece of which is being written by some consultants (I can't fire them or change large chunks of the project/toolchain). I prefer to run my tests in node.js wherever possible (using jsdom when necessary), and usually multiple times per minute (i.e. they need to be fast). I strongly prefer not to have to alt-tab to browser to see results every few seconds.

Because of some technology choices made by the consultants against our wishes (long story), I have to use mocha and chai for tests (I'm used to Jasmine and Jest), and they have no tests/testing workflow setup (again, I can't fire them, out of my hands).

When searching I found this question and its answers. Many of the suggestions are deprecated, or for older versions of e.g. babel.

I've finally reached a point where I've got @babel/core, @babel/register, and @/babel/preset-env installed and ready to go.

So I

mocha --require @babel/register path/to/test.js

With an appropriate preset in .babelrc and I get

regeneratorRuntime is not defined

It's apparently trying to polyfill async/await, even though node supports it.

I don't need to convert every aspect of modern syntax, I only need the import/export statements changed to module.exports and require. I really don't want to have the overhead of the extra transforms/polyfills, I'm just trying to run some tests here. I added @babel/polyfill just to get it working, but can I just set it to transform only import/export statements?

Upvotes: 1

Views: 102

Answers (1)

Brian Adams
Brian Adams

Reputation: 45820

You can add targets to @babel/preset-env to let it know which environment to target.

In this case you'll want to target the current version of Node.js:

presets: [
  [
    '@babel/preset-env',
    {
      targets: {
        node: 'current',
      },
    },
  ],
  ...
]

Upvotes: 1

Related Questions