簡體   English   中英

在 jest.config.js 文件中導入本地文件

[英]Importing local files in `jest.config.js` file

在我的jest.config.js文件中,我需要填充globals屬性。 為了填充globals屬性,我需要需要本地模塊,如下所示:

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
        }
    }
}

使用此配置,我收到以下錯誤:

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

這是我的文件夾結構

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

但是,我可以require節點的內置模塊。 我無法弄清楚為什么會這樣。 關於如何克服這個問題的任何想法?

Jest 是由node發起的,而不是ts-node並且默認情況下它無法解析.ts文件。

可能添加setupFilesAfterEnv會幫助你。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM