使用Mocha测试tsx组件-TypeScript,React和Mocha

问题描述

我有一个组件abc.tsx(在我开始在我的React项目中添加对TS的支持以及升级到Babel7之前,它是abc.js)。该组件可以在npm start上正常编译,并且可以在浏览器中加载它。但是,当我运行测试文件abc.spec.js(使用Mocha 5.x)时,测试失败并显示以下错误

@H_502_12@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

@H_502_12@// 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

@H_502_12@{ "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

@H_502_12@"scripts": { "test": "mocha testSetupFile.js \"./src/**/*.spec.js\"" // } // testSetupFile.js has "require("@babel/register")" among other things

babel.config.json

@H_502_12@// 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标志}