Gatsby + Jest - How to enable support for the experimental syntax 'jsx'? - jestjs

Following Gatsby unit test docs:
https://www.gatsbyjs.com/docs/how-to/testing/unit-testing/#writing-tests
I got this error:
Details:
SyntaxError: ../Projects/gatsby/testing-first-steps/src/components/__tests__/header.js: Support for the experimental syntax 'jsx' isn't currently enabled (9:15):
7 | it("renders correctly", () => {
8 | const tree = renderer
> 9 | .create(<Header siteTitle="Default Starter" />)
| ^
10 | .toJSON()
11 | expect(tree).toMatchSnapshot()
12 | })
Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.

Solved! 🤦
https://www.gatsbyjs.com/docs/how-to/custom-configuration/babel/#how-to-use-a-custom-babelrc-file
Add this:
npm install --save-dev babel-preset-gatsby
then in .babelrc file add this:
{
"presets": [
[
"babel-preset-gatsby",
{
"targets": {
"browsers": [">0.25%", "not dead"]
}
}
]
]
}

Related

Turborepo: SyntaxError: Cannot use import statement outside a module

This is the complete error I get:
cache bypass, force executing 35a9a396ec0cc67c
$ jest --verbose
FAIL __test__/Krebit.test.ts
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/Users/andres/Work/krebit-work/krebit/node_modules/#glazed/datamodel/dist/index.js:41
import { TileLoader } from '#glazed/tile-loader';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import { ethers } from 'ethers';
2 | import { CeramicClient } from '#ceramicnetwork/http-client';
> 3 | import { DataModel } from '#glazed/datamodel';
| ^
4 | import { DIDDataStore } from '#glazed/did-datastore';
5 |
6 | // DID-session
at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (src/lib/ceramic.ts:3:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.909 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
ERROR: command finished with error: command (packages/reputation-passport) yarn run test exited (1)
I have already installed the following packages and added this config:
Packages:
#types/jest: ^28.1.6
jest: ^28.1.3
ts-jest: ^28.0.7
Configuration for jest:
module.exports = {
testEnvironment: 'node',
preset: 'ts-jest',
testMatch: null,
testRegex: '/__test__/.*\\.test\\.(js|ts)$',
testPathIgnorePatterns: ['/node_modules/', '/dist/', '/out/'],
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx'],
clearMocks: true,
globals: {
'ts-jest': {
tsconfig: '<rootDir>/__test__/tsconfig.json',
diagnostics: false
}
}
};
The test I'm implementing is as simple as:
import { ethers } from 'ethers';
import Krebit from '../src';
describe('Krebit Class', () => {
let wallet: ethers.Wallet;
let ethProvider: ethers.providers.Provider;
beforeAll(async () => {
ethProvider = Krebit.lib.ethereum.getProvider();
const pKey = ethers.Wallet.createRandom();
wallet = new ethers.Wallet(pKey, ethProvider);
});
test('The user should be able to connect with her Wallet, EthProvider, and Address', async () => {
console.log(wallet, ethProvider);
});
});
So, I guess the problem comes from the line: ethProvider = Krebit.lib.ethereum.getProvider();, which is importing the package I want to test... If someone needs to read this code, I can share it too...

Cannot test jest with monaco editor - unexpected token

Running jest on the application fails with:
Details:
/home/**/node_modules/monaco-editor/esm/vs/editor/editor.api.js:5
import { EDITOR_DEFAULTS } from './common/config/editorOptions.js';
^
SyntaxError: Unexpected token {
> 1 | import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";
| ^
2 |
3 | /**
4 | * Get create function for the editor.
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
at Object.<anonymous> (src/utils/editor-actions.js:1:1)
Application has installed packages for jest and babel-jest.
Babel config:
const presets = [
[
"#babel/env",
{
targets: {
edge: "17",
firefox: "60",
chrome: "67",
safari: "11.1"
},
useBuiltIns: "usage",
corejs: 3,
}
],
"#babel/preset-react"
];
const plugins = [
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-class-properties",
"babel-plugin-styled-components"
];
module.exports = { presets, plugins };
The import statement as suggested in the docs for lazy loading modules from monaco leads to the esm folder, which jest is not familiar with.
import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";
By default, babel-jest would not transform node_modules and hence anything referencing the monaco-editor would error out. A possible solution is to include monaco-editor package into the compilation step by transformIgnorePatterns as mentioned in the docs
Add these to the jest config:
{
"transformIgnorePatterns": [
"node_modules\/(?!(monaco-editor)\/)"
]
}
PS: If you are using jest-dom, it might start complaining on not implmenting certain features from monaco-editor, you can mock it out with:
jest.mock("monaco-editor/esm/vs/editor/editor.api.js");
The only workaround that helped me in that issue (from here):
In folder __mocks__ create file react-monaco-editor.js with content:
import * as React from 'react';
export default function MonacoEditor() {
return <div />;
}
I have the same issue with Jest and Monaco and to make the tests pass I had to:
Add a moduleNameMapper for monaco-editor: #133 (comment)
Configure a setupTests.js like explained here: stackOverflow
I'm using:
"jest": "^24.9.0"
"babel-jest": "24.9",
"monaco-editor": "^0.20.0"
"react-monaco-editor": "0.33.0",
"monaco-editor-webpack-plugin": "^1.8.2",

Why decorators won't work in Jest with Babel?

I'm trying to get JavaScript decorators to work using Jest and Babel:
./package.json
[...]
"devDependencies": {
[...]
"#babel/core": "7.2.2",
"#babel/plugin-proposal-class-properties": "^7.3.0",
"#babel/plugin-proposal-decorators": "^7.3.0",
"#babel/preset-env": "^7.3.1",
[...]
"jest": "^24.1.0"
},
[...]
"scripts": {
[...]
"jest --no-cache --verbose --config ./test/unit/jest.json"
}
./test/unit/.babelrc
{
"presets": [
[
"#babel/preset-env", {
"targets": {
"node": "current"
},
"modules": "commonjs",
"loose": true,
"debug": true
}
]
],
"plugins": [
["#babel/plugin-proposal-decorators", { "legacy": true }],
["#babel/plugin-proposal-class-properties", { "loose": true}]
]
}
./test/unit/jest.json
{
"modulePaths": [
"<rootDir>/../../src",
"<rootDir>/../../node_modules"
],
"moduleFileExtensions": [
"js",
"json"
],
"testRegex": "\\.spec\\.js$",
"setupFiles": [
"<rootDir>/jest.js"
],
"testEnvironment": "node"
}
./test/unit/jest.js
import 'aurelia-polyfills';
import {Options} from 'aurelia-loader-nodejs';
import {globalize} from 'aurelia-pal-nodejs';
import * as path from 'path';
Options.relativeToDir = path.join(__dirname, '../../src');
globalize();
When I run yarn test I get:
yarn run v1.12.3
$ jest --no-cache --verbose --config ./test/unit/jest.json
#babel/preset-env: `DEBUG` option
Using targets:
{
"node": "11.9"
}
Using modules transform: commonjs
Using plugins:
syntax-async-generators { "node":"11.9" }
syntax-object-rest-spread { "node":"11.9" }
syntax-json-strings { "node":"11.9" }
syntax-optional-catch-binding { "node":"11.9" }
Using polyfills: No polyfills were added, since the `useBuiltIns` option was not set.
console.error internal/process/next_tick.js:81
{ SyntaxError: [...]/src/resources/elements/product/price.js: Support for the experimental syntax 'decorators-legacy' isn't currently enabled (10:1):
8 | import { DataService } from 'services';
9 |
> 10 | #inject(Element, Store, DataService, EventAggregator, I18N)
| ^
11 | #useViewStrategy(new RemoteViewStrategy())
12 | export class ProductPrice {
13 |
at Parser.raise ([...]/node_modules/#babel/parser/lib/index.js:3831:17)
at Parser.expectOnePlugin ([...]/node_modules/#babel/parser/lib/index.js:5158:18)
at Parser.parseDecorator ([...]/node_modules/#babel/parser/lib/index.js:7428:10)
at Parser.parseDecorators ([...]/node_modules/#babel/parser/lib/index.js:7410:30)
at Parser.parseStatement ([...]/node_modules/#babel/parser/lib/index.js:7245:12)
at Parser.parseBlockOrModuleBlockBody ([...]/node_modules/#babel/parser/lib/index.js:7812:25)
at Parser.parseBlockBody ([...]/node_modules/#babel/parser/lib/index.js:7799:10)
at Parser.parseTopLevel ([...]/node_modules/#babel/parser/lib/index.js:7181:10)
at Parser.parse ([...]/node_modules/#babel/parser/lib/index.js:8660:17)
at parse ([...]/node_modules/#babel/parser/lib/index.js:10643:38)
pos: 362,
loc: Position { line: 10, column: 0 },
missingPlugin: [ 'decorators-legacy', 'decorators' ],
code: 'BABEL_PARSE_ERROR' }
console.log test/unit/resources/elements/price.spec.js:25
SyntaxError: [...]/src/resources/elements/product/price.js: Support for the experimental syntax 'decorators-legacy' isn't currently enabled (10:1):
8 | import { DataService } from 'services';
9 |
> 10 | #inject(Element, Store, DataService, EventAggregator, I18N)
| ^
11 | #useViewStrategy(new RemoteViewStrategy())
12 | export class ProductPrice {
13 |
FAIL test/unit/resources/elements/price.spec.js (5.467s)
ProductPrice
✕ should render current (5008ms)
● ProductPrice › should render current
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
18 | });
19 |
> 20 | it('should render current', done => {
| ^
21 | component.create(bootstrap).then(() => {
22 | const currentElement = document.querySelector('.current');
23 | expect(currentElement.innerHTML).toBe('');
at Spec (../../node_modules/jest-jasmine2/build/jasmine/Spec.js:92:20)
at Suite.it (resources/elements/price.spec.js:20:5)
● ProductPrice › should render current
Cannot call ComponentTester.dispose() before ComponentTester.create()
27 |
28 | afterEach(() => {
> 29 | component.dispose();
| ^
30 | });
31 | });
at ComponentTester.Object.<anonymous>.ComponentTester.dispose (../../node_modules/aurelia-testing/dist/commonjs/component-tester.js:66:19)
at Object.dispose (resources/elements/price.spec.js:29:19)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 6.389s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
What I'm doing wrong?
A good hint comes with the error message:
[...]
missingPlugin: [ 'decorators-legacy', 'decorators' ],
code: 'BABEL_PARSE_ERROR' }
The Babel integration of Jest tooks the .babelrc in the first place, for every other file reached from the test it searched only in the project root. In this case the Babel configuration was in ./test/unit.
So putting .babelrc into the project root folder is one possible fix (but not the best). More approaches can be found here.

Dynamically import webpack in Node.js

I´m trying to dynamically import webpack in Node.js
if (condition) {
import('webpack').then(webpack => webpack);
}
However in my terminal I see the following error:
C:\Users\myUser\react\node_modules\#babel\core\lib\transformation\normalize-file.js:209
throw err;
^
SyntaxError: C:\Users\myUser\react\server\index.js: Support for the experimental syntax 'dynamicImport' isn't currently enabled (23:3):
19 |
20 | if (condition) {
> 21 | import('webpack').then(webpack => webpack);
| ^
22 |
Add #babel/plugin-syntax-dynamic-import (https://git.io/vb4Sv) to the 'plugins' section of your Babel config to enable parsing.
I have #babel/plugin-syntax-dynamic-import installed and in my .babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-proposal-class-properties"
]
}
I even tried to add it to the webpack conf file under the rule for .js with loader "babel-loader".
I´m trying to avoid CmJS
const webpack = require('webpack');
In any case I receive the same error and I cannot find a solution. Did anyone go through this? Thanks
add plugins: ["dynamic-import-webpack"] to .babelrc
and also install plug $npm i babel-plugin-dynamic-import-webpack --D

Jest testcase failed due to unexpected token while parsing a flow type in react-native

I am trying to setup jest with my react-native app. I created a simple test case and while running npm test, I get the following error
FAIL __tests__/actionsSpecs.js
● Test suite failed to run
/Users/abc/Projects/MyApp/node_modules/react-native/Libraries/Renderer/src/renderers/shared/hooks/ReactHostOperationHistoryHook.js: Unexpected token (20:4)
18 | & {instanceID: DebugID}
19 | & (
> 20 | | {type: 'mount', payload: string}
| ^
21 | | {type: 'insert child', payload: {toIndex: number, content: string}}
22 | | {type: 'move child', payload: {fromIndex: number, toIndex: number}}
23 | | {type: 'replace children', payload: string}
Basically, it is failing on a flow type declaration. I have tried using flow babel preset and transform-flow-strip-types but that didn't help.
Below is my jest configuration in package.json
"jest": {
"preset": "react-native",
"setupFiles": [
"./setup.js"
],
"transformIgnorePatterns": [ "node_modules/(?!react-native)" ]
}
This is the .babelrc file
{
"presets": ["react-native", "flow"]
}
It looks like the flow preset didn't get rid of the flow types during transpilation but I don't know how to get it to work now.
Please let me know if you know what is wrong.
You need more than just presets, you also need a transform that strips flowtypes. Usually this is done with with the babel plugin babel-plugin-transform-flow-strip-types.
Your .babelrc file should look something like this:
{
"presets": [
"react-native"
],
"plugins": [
"transform-flow-strip-types"
]
}
Edit: Another possibility is that your flow syntax is incorrect, and the transform doesn't know how to handle it. It looks to me from the snippet you've pasted that there's an extra | preceding the object definition on line 20. Does removing that change the output at all?

Resources