【问题标题】:How to make ts-jest work with import/export syntax of the js files that are being imported in my imports?如何使 ts-jest 使用在我的导入中导入的 js 文件的导入/导出语法?
【发布时间】:2021-06-02 12:40:37
【问题描述】:

jest 无法导入我的导入,这导致npm run test 命令在我的bar.ts 文件的第一行出现SyntaxError: Unexpected token 'export' 失败。对于此示例,foo.js 是本地文件,而不是节点模块。我可以将foo.js 更改为foo.ts 并更改bar.ts 中的导入,但这不是解决方案。

我的 src 文件夹中的文件:

  • foo.js:
export const magicNumber = 42; 
  • bar.ts:
import { magicNumber } from './foo.js';

export const secondMagicNumber = magicNumber / 2; 
  • bar.test.ts:
import { secondMagicNumber } from './bar';
import assert from 'assert';

it('should work', function() {
    assert.strictEqual(secondMagicNumber, 21);
});

文件夹中的文件:

  • jest.config.js:
export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
};
  • package.json:
{
  "name": "testing-with-jest",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/jest": "^26.0.20",
    "jest": "^26.6.3",
    "ts-jest": "^26.5.2",
    "typescript": "^4.2.2"
  },
  "type": "module"
}
  • tsconfig.json:
{
  "compilerOptions": {
    "target": "ESNext",                         
    "module": "ESNext",                    
    "outDir": "./dist",                                       
    "strict": true,                          
    "esModuleInterop": true,                  
    "skipLibCheck": true,                     
    "forceConsistentCasingInFileNames": true,
    "declaration": true,
    "moduleResolution": "node"
  },
  "include": ["./src/**/*.ts"]
}

【问题讨论】:

    标签: javascript node.js typescript jestjs ts-jest


    【解决方案1】:

    所以问题在于 ts-jestjest 都很难为 ES6 导入/导出语法设置。我正是这样做的:

    1. 同时安装 jestts-jest >= 27.0.0 版本。
    2. 使用这个最小配置:

    tsconfig.json:

    {
      "compilerOptions": {                    
        "esModuleInterop": true, 
        "allowJs": true                
      }
    }
    

    jest.config.ts:

    export default {
        globals: {
            extensionsToTreatAsEsm: ['.ts', '.js'],
            'ts-jest': {
                useESM: true
            }
        },
    
        preset: 'ts-jest/presets/js-with-ts-esm',
    
        // from https://stackoverflow.com/a/57916712/15076557
        transformIgnorePatterns: [
            'node_modules/(?!(module-that-needs-to-be-transformed)/)' 
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 2019-06-09
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      相关资源
      最近更新 更多