简体   繁体   中英

Importing local files in `jest.config.js` file

In my jest.config.js file, I need to populate globals property. For populating the globals property I need to require local modules, as shown below:

const path = require('path')
const server = require('./server/cfg')

module.exports = {
    rootDir: path.resolve(__dirname),
    moduleFileExtensions: [
        'js',
        'json',
        'vue',
        'ts'
    ],
    moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/src/$1'
    },
    transform: {
        ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest",
        "^.+\\.(js|jsx)?$": "<rootDir>/node_modules/babel-jest",
        "^.+\\.ts$": "<rootDir>/node_modules/ts-jest"
    },
    testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    snapshotSerializers: [
        "jest-serializer-vue"
    ],
    setupFiles: [
      "<rootDir>/globals.js"
    ],
    testEnvironment: "jsdom",
    globals: {
        server: {
            server
        }
    }
}

Whit this configuration, I get the following error:

Error: Cannot find module './server/cfg'

This is my folder structure

server/
   cfg.ts
src/
jest.config.js
webpack.config.js

However, I can require node's built-in modules. I'm not able to figure out why it is happening. Any ideas on how I can overcome this?

Jest is initiated by node , not ts-node and it's not able to resolve the .ts file by default.

Probably adding setupFilesAfterEnv will help you.

jest.config.js
module.exports = {
  // ... your config
  setupFilesAfterEnv: [
    "<rootDir>/environmentWithServer.ts`
  ]
}
environmentWithServer.ts
global.server = require('./server/cfg');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM