如何解决使用Mocha测试tsx组件-TypeScript,React和Mocha
我有一个组件abc.tsx
(在我开始在我的React项目中添加对TS的支持以及升级到Babel7之前,它是abc.js
)。该组件可以在npm start
上正常编译,并且可以在浏览器中加载它。但是,当我运行测试文件abc.spec.js
(使用Mocha 5.x
)时,测试失败并显示以下错误:
import React from 'react';
^^^^^
SyntaxError: Unexpected identifier...
// this error is shown to be in abc.tsx,whose first line is the import
我可以使用*.spec.js
文件来测试*.tsx
文件吗?如果是,这是否与我的配置有关?尽管花了几个小时在网上搜索,但我仍找不到正确的答案。因此,我非常感谢您对此提供的任何帮助。
这是我的配置文件:
webpack.config.js
// all other stuff
resolve: {
extensions: ['.ts','.tsx','.js','.tsx']
},module: {
rules: [
{
test: /\.(ts|js)x?$/,include: Conf.src.js_path,use: 'babel-loader'
}
]
// all other stuff
tsconfig.json
{
"compilerOptions": {
"noImplicitAny": false,"allowSyntheticDefaultImports": true,"sourceMap": true,"target": "es5","jsx": "react","module": "es2015","noImplicitReturns": true,"noUnusedLocals": true,"strict": false,"outDir": "dist","baseUrl": "src","strictNullChecks": true,"allowJs": true
},"include": [
"./src/**/*.ts","./src/**/*.tsx"
],"exclude": ["dist","node_modules"]
}
package.json
"scripts": {
"test": "mocha testSetupFile.js \"./src/**/*.spec.js\"" //
}
// testSetupFile.js has "require("@babel/register")" among other things
babel.config.json
// this does need some clean up for plugins section
{
"presets": [
"@babel/preset-env","@babel/preset-typescript","@babel/react"
],"plugins": [
[
"@babel/plugin-proposal-decorators",{
"legacy": true
}
],["@babel/plugin-proposal-class-properties"],[
"@babel/plugin-transform-spread",{"allowArrayLike" : true}
],["@babel/plugin-proposal-object-rest-spread"],["@babel/plugin-transform-destructuring"],["@babel/plugin-transform-regenerator"],["@babel/plugin-transform-runtime",{"regenerator": true}]
]
}
解决方法
如果要混合使用.js
和.ts(x)
,则需要使用类似ts-node
的名称,并确保在{{1}中启用了--allowJs
标志}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。