When executing a sample test, I get the following error:
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.
I have the following file structure:
│
├── ...
├── src
│ └── ts
│ └── index.ts
├── test
│ └── ts
│ └── index.test.ts
├── ...
In my jest
configuration, I have the following:
"jest": {
"preset": "ts-jest",
"transform": {
"^.+\\.tsx?$": "ts-jest"
}
}
Here is my tsconfig.json
file:
{
"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"
]
}
In index.ts
, I have the following class being exported:
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
};
Lastly, in index.test.ts
, I am importing the file as follows:
import {HelloWorld} from "../../src/ts";
describe('Very first test', () => {
it('A test', () => {
const temp: HelloWorld = new HelloWorld();
expect(temp).not.toBe(null);
});
});
Any thoughts on the issue?
Try changing:
"target": "ESNext"
to
"target": "ES6"
What's happening is that TypeScript is transpiling into JS that's too modern for Jest to understand. If there's still an issue you could try ES5 as well.
It turns out that lit-element
and lit-html
were not being transpiled properly inside of node_modules
. As a solution, I have the following configuration:
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)/)"
]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.