Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node - using jest with esm package

I was wondering how I would incorporate the esm package https://www.npmjs.com/package/esm with jest on a node backend.

I tried setting up a setup file with require("esm") and require("esm")(module) at the very top of the file, but it's still giving me the SyntaxError: Unexpected token error.

I would have previously used node -r esm but jest doesn't support this.

like image 374
A. L Avatar asked Nov 01 '18 04:11

A. L


People also ask

Does Jest support ESM modules?

Jest ships with experimental support for ECMAScript Modules (ESM). The implementation may have bugs and lack features. For the latest status check out the issue and the label on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still considered experimental by Node (as of version 18.8.

Is ESM better than CommonJS?

The conclusion, here, is that ESM is a more secure module system than CJS and last, but not least, ESM is about syntax that cannot be replaced, while in CJS both module and exports can be replaced on the fly within the module itself.

Can ECMAScript be used natively in Node?

Node.js fully supports ECMAScript modules as they are currently specified and provides interoperability between them and its original module format, CommonJS.


1 Answers

When you perform require("esm")(module), think of it as you are creating an esm-transformer function that is pending a file to be transformed into an ES module.

Here's my attempt with node v8+ with:

  • default jest configuration

  • default esm configuration

enter image description here

utils-1.js:

export const add = (a, b) => a + b;

utils-2.js:

export const multiAdd = array => array.reduce((sum, next) => sum + next, 0)

_test_/utils-1.assert.js

import { add } from '../utils-1';

describe('add(a,b)', () => {
  it('should return the addtion of its two inputs', () => {
    expect(add(1,2)).toBe(3);
  });
});

_test_/utils-2.assert.js

import { multiAdd } from '../utils-2';

describe('multiAdd(<Number[]>)', () => {
  it('should return a summation of all array elements', () => {
    expect(multiAdd([1,2,3,4])).toBe(10);
  })
});

_test_/utils.test.js

const esmImport = require('esm')(module);
const utils_1 = esmImport('./utils-1.assert')
const utils_2 = esmImport('./utils-2.assert')

enter image description here

Hope this helps!

like image 198
Jonalogy Avatar answered Oct 16 '22 21:10

Jonalogy