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

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?

Related

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

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"]
}
}
]
]
}

Entry Descriptor Syntax Invalid Configuration

So i'm trying to configure my webpack config to use the entry descriptor syntax as described here.
This is an example of my config:
entry: {
shared: [
'react',
'prop-types',
'lodash',
'moment',
'./src/utils/polyfills.js',
],
index: { import: './src/index.js', dependOn: 'shared' },
}
However, when I run my build I'm constantly seeing errors saying this syntax doesn't match their API.
Start Command: "dev": "webpack --watch --config webpack.client.js"
Error
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.entry should be one of these:
function | object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string]
-> The entry point(s) of the compilation.
Details:
* configuration.entry['index'] should be a string.
-> The string is resolved to a module which is loaded upon startup.
* configuration.entry['index'] should be an array:
[non-empty string]
-> A non-empty array of non-empty strings
* configuration.entry['index'] should be one of these:
[non-empty string]
-> All modules are loaded upon startup. The last one is exported.
* configuration.entry['index'] should be one of these:
non-empty string | [non-empty string]
-> An entry point with name
Has anyone seen this before? Any ideas?
Entry descriptors are a feature introduced in Webpack v5 which is currently in beta. This syntax is not available in Webpack v4. The webpack documentation seems to have switched to v5 already, documentation for v4 can be found here.

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",

Error when trying to use CanvasJS via RequireJS

I'm trying to use CanvasJS inside my project. I'm using RequireJS to manage the modules, and have this in the main script:
define(['domReady',"canvasjs","common-functions"], function(domReady,CanvasJS) {
domReady(function () {
window.CanvasJS = CanvasJS;
init_page_select();
});
});
This is what I have in my requireJS config file for the path:
"paths": {
// other stuff here
"canvasjs": "node_modules/canvasjs/dist/canvasjs.min"
},
I can see the canvasjs.min.js file being grabbed fine - but then I get this weird error:
ReferenceError: intToHexColorString is not defined[Learn More] canvasjs.min.js:7:7042
[33]</n.prototype.render https://www.test.org/2018/js/lib/node_modules/canvasjs/dist/canvasjs.min.js:7:7042
[28]</n.prototype.render https://www.test.org/2018/js/lib/node_modules/canvasjs/dist/canvasjs.min.js:5:14150
n/this.render https://www.test.org/2018/js/lib/node_modules/canvasjs/dist/canvasjs.min.js:8:17771
init_page_select https://www.test.org/2018/js/lib/spot_view_stats.js:83:2
<anonymous> https://www.test.org/2018/js/lib/spot_view_stats.js:4:3
domReady https://www.test.org/2018/js/lib/domready.js:105:13
<anonymous> https://www.test.org/2018/js/lib/spot_view_stats.js:2:2
execCb https://www.test.org/2018/js/lib/require.js:5:12859
check https://www.test.org/2018/js/lib/require.js:5:6575
enable/</< https://www.test.org/2018/js/lib/require.js:5:9031
bind/< https://www.test.org/2018/js/lib/require.js:5:812
emit/< https://www.test.org/2018/js/lib/require.js:5:9497
each https://www.test.org/2018/js/lib/require.js:5:289
emit https://www.test.org/2018/js/lib/require.js:5:9465
check https://www.test.org/2018/js/lib/require.js:5:7169
enable/</< https://www.test.org/2018/js/lib/require.js:5:9031
bind/< https://www.test.org/2018/js/lib/require.js:5:812
emit/< https://www.test.org/2018/js/lib/require.js:5:9497
each https://www.test.org/2018/js/lib/require.js:5:289
emit https://www.test.org/2018/js/lib/require.js:5:9465
check https://www.test.org/2018/js/lib/require.js:5:7169
enable https://www.test.org/2018/js/lib/require.js:5:9358
init https://www.test.org/2018/js/lib/require.js:5:5716
h https://www.test.org/2018/js/lib/require.js:5:4287
completeLoad https://www.test.org/2018/js/lib/require.js:5:12090
onScriptLoad https://www.test.org/2018/js/lib/require.js:5:13014
I'm invoking it with:
var chart = new CanvasJS.Chart("thegraph",
{
title:{
text: impressionText
},
theme: "theme2",
axisX: {
valueFormatString: "MMM-DD-YYYY",
labelAngle: -50
},
axisY:{
valueFormatString: "#0",
title: impressionText
},
data: [
{
type: "line",
showInLegend: true,
legendText: legendText,
dataPoints: dataPoints
}
]
});
chart.render();
Interestingly, if I tell it to load canvasjs.js instead of canvasjs.min.js, I get another error:
ReferenceError: intToHexColorString is not defined[Learn More]
OK so the problem seemed to be my version. For some reason "npm install canvasjs" was installing 1.8.1, but 2.2 was out. As per their request, I updated it to 2.2 and it sorted the problem. It seems weird npm is running such an outdated version though

Use Jest and spread operator without babel?

Is it possible to use the spread operator in code with Jest and without babel if the node engine is 8+?
I am dropping support for Node.js <8 in my app and assumed I could remove all babel dependencies and transpiling from package.json, however npm run jest fails immediately with these types of errors:
FAIL test/workers/repository/onboarding.spec.js
● Test suite failed to run
/Users/me/project/lib/workers/repository/onboarding.js: Unexpected token (13:17)
11 |
12 | async function createOnboardingBranch(inputConfig) {
> 13 | let config = { ...inputConfig };
| ^
Is there any way to get Jest to work without needing to add back all the babel dependencies and configuration?
Node.js version: 8.9.0
Jest version: 20.0.4
jest config in package.json:
"jest": {
"cacheDirectory": ".cache/jest",
"coverageDirectory": "./coverage",
"collectCoverage": true,
"collectCoverageFrom": [
"lib/**/*.js"
],
"coverageReporters": [
"json",
"lcov",
"text-summary"
],
"setupTestFrameworkScriptFile": "./test/chai.js"
},
Edit:
I have been able to narrow my babel configuration down to just one plugin: babel-plugin-transform-object-rest-spread and configure babel in package.json like so:
"babel": {
"plugins": [
"transform-object-rest-spread"
]
},
Taking this out or attempting to use babel-preset env causes Jest to fail on the spread operator again.

Resources