Search code examples
typescriptjestjsts-jest

How to use at modules imports (@) in Jest's globalSetup function with TypeScript?


Using JS hook to invoke TS setupGlobal function (which is using at modules imports, e.g @app/blablabla.ts), I'm getting an error Cannot find module '@config/config'. I've described moduleNameMapper and it's working in tests, but seems it is not in setupGlobal function. How can I fix that?

As I wrote, the moduleNameMapper is described and Jest can understand those (at modules) imports in tests.

jest.config.js

module.exports = {
  roots: ['<rootDir>/src'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  moduleDirectories: ['node_modules', 'src'],
  moduleNameMapper: {
    '@tests-suite/(.*)': '<rootDir>/src/tests/tests-suite/$1',
    '@config/(.*)': '<rootDir>/config/$1',
    '@tests/(.*)': '<rootDir>/src/tests/$1',
    '@src/(.*)': '<rootDir>/src/$1',
  },
  globalSetup: "<rootDir>/src/tests/unit/jestGlobalSetup.js"
}

jestGlobalSetup.js

require("ts-node/register");
module.exports = require('./setupTestEnvironment').default;

setupTestEnvironment.ts

import { dbConnectionManager } from '@src/dbConnectionManager'

// tslint:disable-next-line:no-default-export
export default async () => {
  if (process.env.NODE_ENV === 'test') {
    setupTestEnvironment()
  }
}

const setupTestEnvironment = async () => {
  await dbConnectionManager.awaitConnection()
}

I'm expecting that "at module" imports would be executed in setupGlobal function, but it throws the error.


Solution

  • Okay. The problem is we were using absolute paths got solved by installing ts-jest and adding the next jest.config.js:

        module.exports = {
      roots: [
        '<rootDir>/src',
      ],
      testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
      moduleFileExtensions: [
        'js',
        'json',
        'jsx',
        'node',
        'ts',
        'tsx',
      ],
      moduleDirectories: [
        'node_modules',
        'src',
      ],
      moduleNameMapper: {
        '^@tests\\-suite/(.*)$': '<rootDir>/src/tests/tests-suite/$1',
        '^@admin/(.*)$': '<rootDir>/src/admin/$1',
        '^@common/(.*)$': '<rootDir>/src/common/$1',
        '^@app/(.*)$': '<rootDir>/src/app/$1',
        '^@partners/(.*)$': '<rootDir>/src/partners/$1',
        '^@config/(.*)$': '<rootDir>/config/$1',
        '^@tests/(.*)$': '<rootDir>/src/tests/$1',
        '^@src/(.*)$': '<rootDir>/src/$1',
      },
      setupFilesAfterEnv: [`<rootDir>/src/tests/setup/GlobalSetup.ts`],
      preset: 'ts-jest',
      testMatch: null,
    };
    

    And our run script looks like this "test:jest": "NODE_ENV=test yarn ts-node -r tsconfig-paths/register ./src/tests/setup/testInit.ts"

    And testInit looks like this;

    import { runCLI } from 'jest'
    
    // globalSetup
    async function init() {
      console.log('Initialization')
    
      await runCLI({ config: './jest.config.js', watch: true } as any, [__dirname])
    
      // Do all your initialization stuff
      // I use a setTimeout to simulate true async
      return new Promise<void>((resolve, _reject) => {
        setTimeout(() => {
          console.log('Init finished')
          resolve()
        }, 1000)
      })
    }
    
    // globalTeardown
    async function afterTests(): Promise<void> {
      console.log('End of tests - Execute something')
    }
    
    init()
      .then(() => {
        afterTests()
      })
      // tslint:disable-next-line:no-console
      .catch(e => console.error(e))
    

    GlobalSetup.ts looks like this:

    import { DBConnectionManager } from '@src/DBConnectionManager'
    
    beforeAll(async () => {
      await DBConnectionManager
      .awaitConnection()
    })
    

    So the DBConnectionManager is just a wrapper around TypeORM, which gives us a connection. It is get connected before each test to hit the real test DB. It works for now.