编译 'vuex-typex' npm 包的 'dist/index.js' 并与 Jest 兼容



这个问题最初是在GitHub上作为一个悬而未决的问题提出的。

我在使用 Vue.js、Vuex、TypeScript 和vuex-typex运行 Jest 测试时遇到了语法错误。我对使用 Vue.js、TypeScript 和 Jest 相当陌生。

值得一提的是,有问题的测试是直接针对 Vuex 存储对象 (.ts) 而不是 Vue 组件 (.vue编写的。

这是我得到的错误输出:

Test suite failed to run
.../node_modules/vuex-typex/dist/index.js:19
import { Store } from "vuex";
^^^^^^
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
at Object.<anonymous> (src/store/main.ts:9:18)
...

我正在使用这些工具的以下版本:

"vue": "^2.5.10"
"vuex": "^3.0.0"
"typescript": "^2.6.2"
"vuex-typex": "^3.0.1"
"jest": "^21.2.1"
"jest-vue-preprocessor": "^1.3.1"
"@types/jest": "^21.1.8"
"ts-jest": "^21.2.4"
"typescript-babel-jest": "^1.0.5"

以下是处理测试代码的配置设置:

.babelrc

{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-runtime"],
"env": {
"test": {
"presets": ["env", "stage-2"]
}
}
}

package.json

...
"jest": {
"moduleFileExtensions": [
"js",
"ts",
"vue"
],
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1",
"\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/mocks/file.ts",
"\.(css|less)$": "<rootDir>/mocks/style.ts"
},
"transform": {
".*\.(vue)$": "<rootDir>/node_modules/jest-vue-preprocessor",
".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js",
".*": "<rootDir>/node_modules/babel-jest"
},
"transformIgnorePatterns": [
"<rootDir>/node_modules/(?!vuex-i18n).+\.js$"
],
"testMatch": [
"**/?(*.)spec.ts"
],
"verbose": true
}
...

tsconfig.json

...
"jest": {
"globals": {
"ts-jest": {
"compilerOptions": {
"module": "commonjs"
},
"include": [
"./test/**/*"
]
}
}
}
...

我认为这可能是发布到 npm 的分发代码中的某种编译问题,所以我尝试使用 Babel 手动处理我正在使用的目标的dist/index.js文件:

es2015
stage-2
"browserslist": [ "> 1%", "last 2 versions", "not ie <= 8" ]

这似乎为我解决了这个问题,但我对我的诊断只有部分信心。我在此存储库上没有看到任何其他问题(打开或关闭)表明其他人遇到了此问题。我不想在我的代码中应用误导的解决方法或掩盖潜在的实现问题。

我希望这只是我的简单疏忽或误解。你能提供任何见解吗?您是否或您认识的其他人将这套特定的工具与 Jest 测试一起使用?看起来vuex-typex的测试是用摩卡和柴写的,但我想其他人也一定在 Jest 中使用这个。

我遇到了同样的事情,并努力寻找解决方法。

幸运的是,比我聪明的人想通了,并提交了拉取请求:

https://github.com/mrcrowl/vuex-typex/pull/13

利用它直到它被合并,你应该很高兴。

最新更新