Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot use import statement outside of a module - running with jest in ESM mode #147

Closed
matewilk opened this issue Nov 22, 2022 · 1 comment

Comments

@matewilk
Copy link
Contributor

First off, Thank you for your amazing work 🌟

Describe the bug
I have the following config:

package.json file test command:
"test": "NODE_OPTIONS=--experimental-vm-modules jest", - native support for EcmaScript Modules

jest.config.js:

// jest.config.js
const nextJest = require("next/jest");

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: "./",
});

// Add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const customJestConfig = {
  // Add more setup options before each test is run
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
  moduleDirectories: ["node_modules", "<rootDir>/"],
  testEnvironment: "jest-environment-jsdom",

  moduleNameMapper: {
    // Handle module aliases (this will be automatically configured for you soon)
    "^@/components/(.*)$": "<rootDir>/src/components/$1",
    "^@/pages/(.*)$": "<rootDir>/src/pages/$1",
    "^@/hooks/(.*)$": "<rootDir>/src/hooks/$1",
    "^@/providers/(.*)$": "<rootDir>/src/providers/$1",
    "^@/utils/(.*)$": "<rootDir>/src/utils/$1",
  },

  // allows runing jest in ESM mode
  extensionsToTreatAsEsm: [".ts", ".tsx"],

  setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "ESNext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "noUncheckedIndexedAccess": true,
    "paths": {
      "@/components/*": ["./src/components/*"],
      "@/pages/*": ["./src/pages/*"],
      "@/hooks/*": ["./src/hooks/*"],
      "@/providers/*": ["./src/providers/*"],
      "@/utils/*": ["./src/utils/*"]
    }
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "**/*.cjs",
    "**/*.mjs",
    "src/utils/ethereum.ts"
  ],
  "exclude": ["node_modules"]
}

To Reproduce
Run jest in ESM mode (with typescript) with a component using useDebounce hook.

Behaviour when running npm run test:

Jest encountered an unexpected token
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

Details:

/Users/matewilk/Workspace/crypto-p2p/node_modules/use-debounce/dist/index.module.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import{useRef as r,useEffect as n,useMemo as t,useCallback as u,useState as e}from"react";function c(u,e,c){var i=this,a=r(null),o=r(0),f=r(null),l=r([]),m=r(),v=r(),d=r(u),p=r(!0);n(function(){d.current=u},[u]);var g=!e&&0!==e&&"undefined"!=typeof window;if("function"!=typeof u)throw new TypeError("Expected a function");e=+e||0;var w=!!(c=c||{}).leading,s=!("trailing"in c)||!!c.trailing,x="maxWait"in c,y=x?Math.max(+c.maxWait||0,e):null;n(function(){return p.current=!0,function(){p.current=!1}},[]);var h=t(function(){var r=function(r){var n=l.current,t=m.current;return l.current=m.current=null,o.current=r,v.current=d.current.apply(t,n)},n=function(r,n){g&&cancelAnimationFrame(f.current),f.current=g?requestAnimationFrame(r):setTimeout(r,n)},t=function(r){if(!p.current)return!1;var n=r-a.current;return!a.current||n>=e||n<0||x&&r-o.current>=y},u=function(n){return f.current=null,s&&l.current?r(n):(l.current=m.current=null,v.current)},c=function r(){var c=Date.now();if(t(c))return u(c);if(p.current){var i=e-(c-a.current),f=x?Math.min(i,y-(c-o.current)):i;n(r,f)}},h=function(){var u=Date.now(),d=t(u);if(l.current=[].slice.call(arguments),m.current=i,a.current=u,d){if(!f.current&&p.current)return o.current=a.current,n(c,e),w?r(a.current):v.current;if(x)return n(c,e),r(a.current)}return f.current||n(c,e),v.current};return h.cancel=function(){f.current&&(g?cancelAnimationFrame(f.current):clearTimeout(f.current)),o.current=0,l.current=a.current=m.current=f.current=null},h.isPending=function(){return!!f.current},h.flush=function(){return f.current?u(Date.now()):v.current},h},[w,x,e,y,s,g]);return h}function i(r,n){return r===n}function a(r){return"function"==typeof r?function(){return r}:r}function o(n,t,o){var f,l,m=o&&o.equalityFn||i,v=(f=e(a(n)),l=f[1],[f[0],u(function(r){return l(a(r))},[])]),d=v[0],p=v[1],g=c(u(function(r){return p(r)},[p]),t,o),w=r(n);return m(w.current,n)||(g(n),w.current=n),[d,g]}function f(r,n,t){var u=void 0===t?{}:t,e=u.leading,i=u.trailing;return c(r,n,{maxWait:n,leading:void 0===e||e,trailing:void 0===i||i})}export{o as useDebounce,c as useDebouncedCallback,f as useThrottledCallback};
                                                                                  ^^^^^^

SyntaxError: Cannot use import statement outside a module

Expected behavior
Running tests without the error.
The moment I remove useDebounce hook from my component all is running smoothly again.

use-debounce version:
8.0.4
jest: 29.3.1
typescript: 4.8.4

@xnimorz
Copy link
Owner

xnimorz commented Nov 24, 2022

Hey @matewilk ! Thanks for the contribution. I'll check and cut a new release soon

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants