Typescript,ts-jest导入.ts文件而不是同名的.js文件

laik7k3q  于 6个月前  发布在  Jest
关注(0)|答案(1)|浏览(76)

我有一个测试文件和测试导入的文件。类似于:

// fileA.spec.ts

import fileA from "services/fileA"

// do stuff....

字符串
现在我有另一个构建过程,它可能会运行并生成等效的JS文件,这给我留下了一个文件结构,如下所示

src
- services
-- fileA.ts
-- fileA.js --> this is generated by a build script
-- fileA.spec.ts


如果我在运行创建JS文件的脚本之前**运行jest测试,测试运行正常并通过。但是,如果我在之后运行它们,则导入尝试导入JS文件并导致错误。
我如何配置typescript或TS-jest来解析导入到TS文件并忽略JS文件?下面是我的配置文件。

// tsconfig.json 

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "baseUrl": "scripts",
    "lib": [ "dom", "es7" ],
    "module": "ES2015",
    "moduleResolution": "Node",
    "esModuleInterop": true,
    "noEmitOnError": true,
    "noImplicitAny": true,
    "target": "es5",
    "sourceMap": true,
    "paths": {
      "config/*": ["config/*"],
      "interfaces/*": ["interfaces/*"],
      "modules/*": ["modules/*"],
      "services/*": ["services/*"],
      "third-party/*": ["third-party/*"],
      "vue-components/*": ["vue-components/*"]
    }
  },
  "include": [
    "**/*.ts",
    "**/*.vue"
  ]
}
// jest.config.js

const { pathsToModuleNameMapper } = require('ts-jest')
const { compilerOptions } = require('./tsconfig')

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  testEnvironment: 'jsdom',
  roots: ['<rootDir>'],
  moduleDirectories: ["node_modules", "<rootDir>"],
  modulePaths: [compilerOptions.baseUrl],
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
  moduleFileExtensions: ["js", "ts", "json", "vue"],
  transform: {
    // process `*.ts` files with `ts-jest`
    "^.+\\.ts$": "ts-jest",
    // process `*.vue` files with `vue-jest`
    ".*\\.vue$": "vue-jest"
  },
  testRegex: [
    "**/*.spec.ts",
  ],
  setupFilesAfterEnv: ["./jest-setup.ts"]
};

的字符串

tzcvj98z

tzcvj98z1#

我认为如果不检查你的主项目配置文件,很难回答这个问题。然而,一些通用的提示可能对你有用。你可以通过调整tsScript. json和Jest配置中的配置,配置TypeScript和Jest来解析TS文件的导入,忽略JS文件。

1.更新tsconfig.json:

确保你的tslog.json有以下编译器选项:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "esModuleInterop": true,
    // other options...

    "baseUrl": "./",
    "paths": {
      "*": ["src/*"]
    }
  }
}

字符串
“baseUrl”和“paths”设置帮助TypeScript基于src目录解析导入。

2.更新Jest配置(jest.js.js或package.json中):

添加transform配置以显式地告诉Jest使用ts-jest并忽略JavaScript文件:

// jest.config.js
module.exports = {
  transform: {
    '^.+\\.ts$': 'ts-jest'
  },
  // other Jest configurations...
};

3.确保安装了ts-jest:

确保你安装了ts-jest作为开发依赖:

npm install --save-dev ts-jest

4.运行Jest:

完成这些更改后,运行Jest测试。它现在应该将导入解析为TypeScript文件并忽略JavaScript文件。
这些配置有助于TypeScript和Jest协同工作,确保TypeScript文件在导入解析过程中被优先处理。这应该可以解决Jest尝试导入生成的JS文件时所面临的问题。

相关问题