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

[v5] jest fails to run #96

Closed
Dakuan opened this issue Jul 25, 2021 · 7 comments
Closed

[v5] jest fails to run #96

Dakuan opened this issue Jul 25, 2021 · 7 comments

Comments

@Dakuan
Copy link

Dakuan commented Jul 25, 2021

I've just bumped my code to v5 as I'm currently experiencing the #65 bug often. My tests dont run however (detail below). I'm guessing this is because the current build target and module ts settings are super modern.

Could they be downgraded to "target":"es5" and "module": "commonjs" ?

ps congrats on the first v5 alpha!

  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     • 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/en/configuration.html

    Details:

    /home/circleci/project/node_modules/redlock/dist/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { randomBytes, createHash } from "crypto";
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import Redlock, { Lock } from "redlock";
@mike-marcacci
Copy link
Owner

Thanks for trying out the alpha! This is really great to note, and it may be that the ecosystem isn't actually ready for es modules. I wasn't aware that jest itself even attempted to parse dependencies (that's quite surprising behavior for something that I thought was a simple test runner).

Would you mind telling me a bit more about your setup here? Are you compiling your code through TS or babel, or packaging them up in some way with webpack or an equivalent? Also, what version of node is being run here?

Thanks again for the rapid help testing these changes in real-world applications!

@Dakuan
Copy link
Author

Dakuan commented Jul 26, 2021

sure, im on node14 and its a plain olde express app

my jest config is like so:

// eslint-disable-next-line no-undef
module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  setupFilesAfterEnv: ["<rootDir>/test/utils/setup.ts"],
  modulePathIgnorePatterns: ["<rootDir>/build/"],
  coverageThreshold: {
    global: {
      branches: 100,
      functions: 100,
      lines: 100,
    },
  },
};

my ts is compliled inside my docker container:

dockerfile:

RUN npm install
RUN npm run build

package json:

  "scripts": {
    "build": "./node_modules/.bin/tsc --project ./tsconfig.production.json",
}

1st ts config tsconfig.production.json

{
  "extends": "./tsconfig",
  "compilerOptions": {
    "sourceMap": true,
    "inlineSources": true,
    "sourceRoot": "/"
  }
}

2nd ts config tsconfig.json

{
  
  "compilerOptions": {
    "paths": {
      "*": ["./node_modules/*", "./src/types/*"],
      "@src/*": ["./src/*"],
    },
    // "include": ["src/**/*", "test/**/*"],
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./build" /* Redirect output structure to the directory. */,
    "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true /* Enable all strict type-checking options. */,
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
    // "noUncheckedIndexedAccess": true,      /* Include 'undefined' in index signature results */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    //* Type declaration files to be included in compilation. */,
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true /* Skip type checking of declaration files. */,
    "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
  }
}

(theres two of them because: https://docs.sentry.io/platforms/node/typescript/#sentry-sdk-and-source-maps-with-typescript)

no webpack or babel as far as i know, just the ts compiler.

@Dakuan
Copy link
Author

Dakuan commented Jul 26, 2021

Thanks for trying out the alpha! This is really great to note, and it may be that the ecosystem isn't actually ready for es modules. I wasn't aware that jest itself even attempted to parse dependencies (that's quite surprising behavior for something that I thought was a simple test runner).

it doesn't parse anything in node_modules unless you ask it to. There are times when you need it to, eg for react native: https://jestjs.io/docs/tutorial-react-native#transformignorepatterns-customization. This workaround doesnt work for me as the files are already transpiled - just not into a format my environment can work with.

@Dakuan
Copy link
Author

Dakuan commented Jul 26, 2021

just bumped myself to node16, same result

@SimenB
Copy link

SimenB commented Aug 25, 2021

Jest executes all code in a vm, and vm's support for ESM is sorta sketchy still (see first link in the error in the OP: https://jestjs.io/docs/ecmascript-modules)

Best solution for Jest here is to ship a CJS implementation (in addition to the ESM one) referenced in main and using exports for the ESM one: https://nodejs.org/api/packages.html#packages_package_entry_points

(note that Jest does not support this field yet, which is why main is still needed)

@Dakuan
Copy link
Author

Dakuan commented Nov 4, 2021

#114 should fix

@mike-marcacci
Copy link
Owner

I just published v5.0.0-beta.1 which should fix this.

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

3 participants