Reputation: 2444
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?
Upvotes: 0
Views: 6050
Reputation: 2444
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)sx?$": "babel-jest"
},
"transformIgnorePatterns": [
"node_modules/(?!(lit-element|lit-html)/)"
]
}
Upvotes: 2
Reputation: 1753
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.
Upvotes: 1