Amtrak
Amtrak

Reputation: 21

CommonJS require won't work inside Jest test file

I am testing my backend with Jest, but I keep getting this error

\node_modules\generate-key\lib\generate.coffee:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){rn = (max) ->
                                                                                              ^

SyntaxError: Unexpected token '>'

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
  at Object.<anonymous> (node_modules/generate-key/index.js:2:18)

This is my jest config file:

   module.exports = { clearMocks: true, coverageDirectory: 'coverage', testEnvironment: 'node',moduleFileExtensions: ['ts', 'js', 'json', 'node'] };

My test file:

/* eslint-disable no-undef */
const { getConvertedKind } = require('../common');

test('check', () => {
  expect(3).toBe(3);
});

The imported function:

exports.getConvertedKind = kind => {
  const kinds = {
    cinemaPass: 'cinema',
    hotelPass: 'hotel',
    boardingPass: 'flight',
    coupon: 'coupon',
    eventTicket: 'event',
    transit: 'transit',
    storeCard: 'wallet',
    offer: 'offer'
  };
  return kinds[String(kind)] || null;
};

package.json:

"scripts": {
"start": "nodemon server.js",
"start:prod": "NODE_ENV=production nodemon server.js",
"debug": "ndb server.js",
"test": "jest --config ./jest.config.js"

}

Upvotes: 2

Views: 473

Answers (1)

Teneff
Teneff

Reputation: 32148

It seems like you're trying to load a .coffee file and by default jest doesn't transform node_modules.

You can check the transformIgnorePatterns option and try something like:

transformIgnorePatterns: ["node_modules/(?!generate-key)"],

Upvotes: 1

Related Questions