Eric Hartford
Eric Hartford

Reputation: 18032

next.js + typescript + jest Unexpected token 'export'

When I try to run jest in my Typescript Next.js project, I get this error:

    Details:

    node_modules/d3-scale/src/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export {
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

       7 | import { useRouter } from 'next/router';
       8 | import { gql } from '@apollo/client';
    >  9 | import { scaleLinear } from 'd3-scale';

I have already tried to add d3-scale to transformIgnorePatterns in my jest config.

const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './',
});
const customJestConfig = {
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/', '<rootDir>/pages/test.tsx'],
  moduleNameMapper: {
    '\\.(scss|sass|css)$': 'identity-obj-proxy',
  },
  transform: {
    '\\.[jt]sx?$': 'babel-jest',
  },
  transformIgnorePatterns: [
    '/node_modules/(?!d3-scale)',
  ],
};
module.exports = createJestConfig(customJestConfig);

Upvotes: 0

Views: 992

Answers (1)

Kaiser theDev
Kaiser theDev

Reputation: 31

You can't override transformIgnorePatterns in Next.js, only extend it.

A valid workaround can be (inside your jest.config.js):

async function jestConfig() {
  const nextJestConfig = await createJestConfig(customJestConfig)()
  nextJestConfig.transformIgnorePatterns[0] = '/node_modules/(?!d3-scale)/'
  return nextJestConfig
}

module.exports = jestConfig
//module.exports = createJestConfig(customJestConfig)

Upvotes: 3

Related Questions