Jest Custom Test Environment Cannot Find Absolute Imported Path

Viewed 275

TL;DR: I can't import absolute paths in a Jest custom test environment. Simplified repo here: https://github.com/kyle-banner/ts-customtestenvironment-jest

Jest and/or Typescript cannot find the modules in the top-level src/* directory of my project when creating a custom test environment

The error I receive is as follows:

 FAIL  path/to/test/something.integration.test.ts
  ● Test suite failed to run

    Cannot find module 'src/config'

My jest.config.js is as follows:

/* eslint-disable */
const { pathsToModuleNameMapper } = require('ts-jest/utils');

module.exports = {
  testEnvironment: './src/testUtils/testEnvironment.ts',
  preset: 'ts-jest',
  collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
  coveragePathIgnorePatterns: ['node_modules', 'src/typings', 'enumConversion'],
  testPathIgnorePatterns: ['build/', 'node_modules/'],
  moduleNameMapper: pathsToModuleNameMapper({
      "src/*": ["src/*"],
    }, { prefix: '<rootDir>/' } )
};

My tsconfig.json is as follows:

{
    "compilerOptions": {
        "allowJs": true,
        "esModuleInterop": true,
        "outDir": "build",
        "module": "commonjs",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "target": "es6",
        "typeRoots": [
            "./src/typings",
            "node_modules/@types"
        ],
        "baseUrl": ".",
        "paths": {
            "src/*": [
                "src/*"
            ]
        }
    },
    "include": [
        "src/**/*.ts",
        "src/**/*.js",
        "src/**/*.json"
    ],
    "exclude": [
        "**/*.test.ts"
    ]
}

My experimental testEnvironment.ts is as follows:

const NodeEnvironment = require('jest-environment-node');
import config from 'src/config';

class CustomEnvironment extends NodeEnvironment {
  constructor(config, context) {
    super(config, context);
  }

  async setup() {
    await super.setup();
    this.global.someGlobalObject = { key: config };
  }

  async teardown() {
    await super.teardown();
  }
}

module.exports = CustomEnvironment;

The entire problem is the import config from 'src/config'; line. I've tried a number of different config options with no luck. I don't know how to import from any file under the top-level src/ directory. The src directory is not recognized in the testEnvironment.ts import statement.

It’s worth noting that relative import paths work (e.g. import config from './src/config';) but I can't use relative paths.

Using jest 27.2.1, ts-jest 27.0.5

0 Answers
Related