[执行样本测试时,出现以下错误:
Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
我具有以下文件结构:
│
├── ...
├── src
│ └── ts
│ └── index.ts
├── test
│ └── ts
│ └── index.test.ts
├── ...
在我的jest
配置中,我具有以下内容:
"jest": {
"preset": "ts-jest",
"transform": {
"^.+\\.tsx?$": "ts-jest"
}
}
这是我的tsconfig.json
文件:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"declaration": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"module": "CommonJS",
"moduleResolution": "Node",
"noImplicitAny": true,
"outDir": "./build",
"removeComments": false,
"sourceMap": true,
"target": "ESNext"
},
"exclude": [
"node_modules"
],
"include": [
"src/**/*"
],
"typeRoots": [
"node_modules/@types"
]
}
在index.ts
中,我正在导出以下类:
import {LitElement, html, customElement, property} from 'lit-element';
@customElement('hello-world')
class HelloWorld extends LitElement {
@property({type: String}) title: string = "default title";
@property({type: String}) description: string = "default description";
render() {
return html`
<style>
.container {
padding: 30px;
text-align: center;
background: #c8e7fd;
}
.container h1 {
font-size: 50px;
}
</style>
<div class="container">
<h1>${this.title}</h1>
<p>${this.description}</p>
</div>
`;
}
}
export {
HelloWorld
};
最后,在index.test.ts
中,我正在如下导入文件:
import {HelloWorld} from "../../src/ts";
describe('Very first test', () => {
it('A test', () => {
const temp: HelloWorld = new HelloWorld();
expect(temp).not.toBe(null);
});
});
对这个问题有任何想法吗?
"target": "ESNext"
to
"target": "ES6"
发生的事情是TypeScript正在转换为Jest无法理解的JS。如果仍然有问题,您也可以尝试ES5。
lit-element
和lit-html
在node_modules
内部未正确转译。作为解决方案,我有以下配置:babel.config.json
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "usage",
"corejs": 2
}
]
],
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"decoratorsBeforeExport": true
}
],
"@babel/proposal-class-properties"
]
}
jest.config.js
module.exports = { "transform": { "^.+\\.(j|t)s?$": "babel-jest" }, "transformIgnorePatterns": [ "node_modules/(?!(lit-element|lit-html)/)" ] }