If you recently bootstrapped a project with Nx and NestJs you might encounter this error when running your first tests:

  ● Test suite failed to run

    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/local/Projects/code/node_modules/uuid/dist/esm-browser/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

      at Runtime.createScriptFromCode (../../node_modules/jest-runner/node_modules/jest-runtime/build/index.js:1773:14)
      at Object.<anonymous> (../../node_modules/@nestjs/common/decorators/core/injectable.decorator.js:4:16)

This is caused by Jest 28 that does not handle all type of export properly, (see this issue for more details)[https://github.com/facebook/jest/issues/9771].

Fix issue

Add a custom resolver script

Create this file: scripts/patched-jest-resolver.js:

// From https://github.com/nrwl/nx/blob/e43971805916a2c8f6be82a11c531d85ab6d95c5/scripts/patched-jest-resolver.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const ts = require("typescript");
const fs = require("fs");

/**
 * Custom resolver which will respect package exports (until Jest supports it natively
 * by resolving https://github.com/facebook/jest/issues/9771)
 */
const enhancedResolver = require("enhanced-resolve").create.sync({
  conditionNames: ["require", "node", "default"],
  extensions: [".js", ".json", ".node", ".ts", ".tsx"],
});

function getCompilerSetup(rootDir) {
  const tsConfigPath =
    ts.findConfigFile(rootDir, ts.sys.fileExists, "tsconfig.spec.json") ||
    ts.findConfigFile(rootDir, ts.sys.fileExists, "tsconfig.test.json") ||
    ts.findConfigFile(rootDir, ts.sys.fileExists, "tsconfig.jest.json");
  if (!tsConfigPath) {
    console.error(
      `Cannot locate a tsconfig.spec.json. Please create one at ${rootDir}/tsconfig.spec.json`
    );
  }
  const readResult = ts.readConfigFile(tsConfigPath, ts.sys.readFile);
  const config = ts.parseJsonConfigFileContent(
    readResult.config,
    ts.sys,
    path_1.dirname(tsConfigPath)
  );
  const compilerOptions = config.options;
  const host = ts.createCompilerHost(compilerOptions, true);
  return { compilerOptions, host };
}
let compilerSetup;

if (
  process.argv[1].indexOf("jest-worker") > -1 ||
  (process.argv.length >= 4 && process.argv[3].split(":")[1] === "test")
) {
  const root = path_1.join(__dirname, "..", "tmp", "unit");
  try {
    if (!fs.existsSync(root)) {
      fs.mkdirSync(root);
    }
  } catch (_err) {}
  process.env.NX_WORKSPACE_ROOT_PATH = root;
}

module.exports = function (path, options) {
  if (path === "jest-sequencer-@jest/test-sequencer") return;
  const ext = path_1.extname(path);
  if (
    ext === ".css" ||
    ext === ".scss" ||
    ext === ".sass" ||
    ext === ".less" ||
    ext === ".styl"
  ) {
    return require.resolve("identity-obj-proxy");
  }
  // Try to use the defaultResolver
  try {
    if (path.startsWith("@nrwl/")) throw new Error("custom resolution");
    if (path.startsWith("nx/")) throw new Error("custom resolution");

    if (path.indexOf("@nrwl/workspace") > -1) {
      throw "Reference to local Nx package found. Use local version instead.";
    }

    // Global modules which must be resolved by defaultResolver
    if (["fs", "http", "path"].includes(path)) {
      return options.defaultResolver(path, options);
    }

    return enhancedResolver(options.basedir, path);
  } catch (e) {
    // Fallback to using typescript
    compilerSetup = compilerSetup || getCompilerSetup(options.rootDir);
    const { compilerOptions, host } = compilerSetup;
    return ts.resolveModuleName(path, options.basedir, compilerOptions, host)
      .resolvedModule.resolvedFileName;
  }
};

Update jest.preset.js

You’ll need to add a custom resolver to your jest.preset.js:

// jest.preset.js
const nxPreset = require("@nrwl/jest/preset").default;

module.exports = {
  ...nxPreset,
  // Notice the `../../` this is because when you run tests from Nx root
  // you are 2 dir deep in your repo
  resolver: "../../scripts/patched-jest-resolver.js",
};

Update your package.json

Add the enhanced-resolve dependencies to your package.json: yarn --dev enhanced-resolve.

That’s all ! Your testsuite should work as expected.