打字稿"声明全局"阻止 Jest 测试套件运行



我的应用程序使用react,redux和jest有一个打字稿文件,其中包含以下代码:

declare global {
interface Window { eventSource: any;}
class EventSource {
errorers: any;
onerror: any;
onmessage: () => void;
addEventListener(event: string, cb: () => void): void;
constructor(name: string);
}
}

我正在使用开玩笑的测试框架在应用程序中使用 es6 javascript 的其他区域上运行测试,并且它们工作正常。 不幸的是,由于以下错误,有两个测试套件无法运行,另一个测试套件也是如此:

/Users/blyncsy/Documents/blyncsyu/client/app/bundles/analytic/data-hub.ts:3
declare global {
^^^^^^
SyntaxError: Unexpected identifier
at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:321:12)
at Object.<anonymous> (app/bundles/Pulse/actions/odAnalyzerActions.js:2:16)
at Object.<anonymous> (app/bundles/Pulse/containers/od-analyzer/ODLineRenderer.js:6:26)

如果上面列出的文件被注释掉,则同一打字稿文件的其他部分会搞砸测试运行程序。 在第一个测试套件中正在测试的操作文件中引用此文件,并且第二个测试套件正在测试的文件中引用此文件中的操作。 我假设在测试遇到此.ts文件之前需要做一些事情来预编译此.ts文件,但是我一直无法弄清楚如何做到这一点。 这是 webpack 配置:

/* eslint comma-dangle: ["error",
{"functions": "never", "arrays": "only-multiline", "objects":
"only-multiline"} ] */
const webpack = require('webpack');
const pathLib = require('path');
const devBuild = process.env.NODE_ENV !== 'production';
const config = {
entry: [
'es5-shim/es5-shim',
'es5-shim/es5-sham',
'babel-polyfill',
'./app/bundles/analytic',
'./app/bundles/Pulse/startup/registration',
],
output: {
filename: 'webpack-bundle.js',
path: pathLib.resolve(__dirname, '../app/assets/webpack'),
},
devtool: "source-map",
resolve: {
extensions: [".ts", ".tsx", '.js', '.jsx'],
},
plugins: [
new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }),
],
module: {
rules: [
{
test: /travel-info-type.ts/,
use: [{
loader: 'expose-loader',
options: 'TravelInfoType'
}]
},
{
test: /heatmap-getter.ts/,
use: [{
loader: 'expose-loader',
options: 'HeatmapGetter'
}]
},
{
test: /data-hub.ts/,
use: [{
loader: 'expose-loader',
options: 'DataHub'
}]
},
{
test: require.resolve('react'),
use: {
loader: 'imports-loader',
options: {
shim: 'es5-shim/es5-shim',
sham: 'es5-shim/es5-sham',
}
},
},
{
test: /.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/,
},
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{ test: /.tsx?$/, loader: "awesome-typescript-loader" },
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ enforce: "pre", test: /.js$/, loader: "source-map-loader" },
// Extract css files
{
test: /.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
};
module.exports = config;
if (devBuild) {
console.log('Webpack dev build for Rails'); // eslint-disable-line no-console
module.exports.devtool = 'eval-source-map';
} else {
console.log('Webpack production build for Rails'); // eslint-disable-line no-console
}

任何帮助不胜感激!

你的错误

/Users/blyncsy/Documents/blyncsyu/client/app/bundles/analytic/data-hub.ts:3

指示 Jest 正在尝试运行.ts文件。您需要使用ts-jest来转换此 TS 文件。

更多

这记录在 TypeScript 文档中: https://facebook.github.io/jest/docs/getting-started.html#using-typescript

最新更新