cod*_*ero 7 typescript jestjs ts-jest
我正在使用 jest 在 lib 上运行一些测试,在升级现在导出到 es6 的 lib 后,我收到错误“无法在模块外使用 import 语句”,在升级之前测试工作得很好。
我正在使用的 jest.config.js 文件:
module.exports = {
roots: ['<rootDir>/src/'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.ts?$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};
Run Code Online (Sandbox Code Playgroud)
tsconfig.json 文件:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"lib": ["es6", "dom"],
"types": ["jest"],
"sourceMap": true,
"jsx": "react",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"strict": true,
"emitDecoratorMetadata": true,
"importHelpers": true,
"noEmitHelpers": true,
"noFallthroughCasesInSwitch": true,
"strictFunctionTypes": false,
"pretty": true,
"removeComments": false,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"experimentalDecorators": true,
"baseUrl": "./"
}
}
Run Code Online (Sandbox Code Playgroud)
最后是 babel.config.js 文件:
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
ie: '11',
},
},
],
'@babel/typescript',
],
plugins: [
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-transform-object-assign',
'@babel/plugin-transform-runtime',
],
env: {
development: {},
production: {
plugins: ['transform-dev-warning'],
ignore: ['**/test/'],
},
test: {
sourceMaps: 'both',
},
},
};
Run Code Online (Sandbox Code Playgroud)
我已经尝试了几乎所有可以在网上找到的解决方案,但似乎没有任何效果。如果有人能帮助我那就太好了,提前致谢!
这是很常见的问题,因为使用 ( import) esmjs 样式会导致该问题。在本例中,包是sip.js.
该解决方案也很常见,我们只需简单地配置jest使用 magic option 来转换该包即可transformIgnorePatterns。另外,还告诉我们也tsc编译该esm包。
简而言之,您需要执行以下操作:
jest.config.js
module.exports = {
// ...
transform: {
'^.+\\(t|j)sx?$': 'ts-jest', // transpile both `ts` + `js` files
},
transformIgnorePatterns: [`/node_modules/(?!(sip\.js))`] // Keep `sip.js` to get transpiled as well
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6570 次 |
| 最近记录: |