chartjs / chartjs-adapter-luxon

Luxon adapter for Chart.js
MIT License
33 stars 24 forks source link

Jest ESM import (resolved) #91

Closed pieterjandebruyne closed 1 year ago

pieterjandebruyne commented 1 year ago

Versions: "chart.js": "^4.2.1", "chartjs-adapter-luxon": "^1.3.1",

Issue: import 'chartjs-adapter-luxon' crashes on jest tests.

Error:

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

/Users/dev/project-x/node_modules/chartjs-adapter-luxon/dist/chartjs-adapter-luxon.esm.js:7
    import { _adapters } from 'chart.js';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module
      12 | } from 'chart.js'
      13 |
    > 14 | import 'chartjs-adapter-luxon'
         | ^

I already found a workaround for this myself but I think it could be helpful for other people here trying to do the same in a typescript esm project:

in jest.config.ts add:

const esModules = ['chartjs-adapter-luxon'].join('|')
// inside config object
transformIgnorePatterns: [`/node_modules/(?!${esModules})`],

in tsconfig.json make sure you have:

"compilerOptions": {"allowJs": true, ... }
benmccann commented 1 year ago

Jest is a pile of junk. I'd suggest using Vitest instead

CaduGomes commented 1 year ago

Just adding some more informations about the workaround. If your project are using Next.js then the transformIgnorePatterns should be added like this:

const esModules = ['chartjs-adapter-luxon'].join('|');
const customJestConfig = {...};

const jestConfig = async () => {
    const nextJestConfig = await createJestConfig(customJestConfig)();
    nextJestConfig.transformIgnorePatterns[0] = `/node_modules/(?!${esModules})`;
    return nextJestConfig;
};

@pieterjandebruyne, thanks for the workaround!