Error with react testing library and create react app (SyntaxError: Unexpected identifier import ArrayFrom from "./polyfills/array.from.mjs";) - jestjs

I know when you have a bare React app, you config webpack to use babel and then jest is using the babel configuration to compile the modules.
Now I have an app created with create-react-app. With a package.json as follows:
{
"name": "it does not matter",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-redux": "^7.2.0",
"react-redux-loading": "^1.0.1",
"react-router-dom": "^5.1.2",
"react-scripts": "1.1.1",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
With things being like that I wrote the simplest possible test, that passes as green:
import React from "react";
import ReactDOM from "react-dom";
it("renders LoggedUser without crashing", () => {
const div = document.createElement("div");
const name = "::name::";
const avatarURL = "::avatarURL::";
const loggedUser = { name, avatarURL };
ReactDOM.render(<LoggedUser loggedUser={loggedUser} />, div);
});
Now I follow the create react app docs to add the React testing library:
https://create-react-app.dev/docs/running-tests/#option-2-react-testing-library
I follow the steps but when running the test it complaints:
import React from "react";
import { render } from "#testing-library/react";
import { LoggedUser } from "../components/LoggedUser";
it("renders LoggedUser without crashing", () => {
const name = "::name::";
const avatarURL = "::avatarURL::";
const loggedUser = { name, avatarURL };
render(<LoggedUser loggedUser={loggedUser} />);
});
import ArrayFrom from "./polyfills/array.from.mjs";
^^^^^^^^^
SyntaxError: Unexpected identifier
In my package I have only added the dependencies:
"devDependencies": {
"#testing-library/jest-dom": "^5.5.0",
"#testing-library/react": "^10.0.4"
}
And as the docs suggested created a src/setupTests.js file
// react-testing-library renders your components to document.body,
// this adds jest-dom's custom assertions
import '#testing-library/jest-dom/extend-expect';
I have tried many things (a .babelrc file with and without a jest.config file...) but I was unable to make the test pass, when fixing one problem another one appeared...
Maybe sb is familiar with this problem and its possible solutions.
Cheers!

Well, in the end what I was trying to do was very twisted because I didn't know very well the webpack-babel-jest delegation when using the create-react-app boilerplate...
So I made another app from scratch and it did work, so I just updated in my real app the "react-scripts": "3.x.x" to make it work.
I apologize for all this hassle, anyway digging in the boilerplate was quite educational.
Thank you anyway!

Related

React front end with Node express back end. Terminal crashes every time I make a change

I am building my first application using a React Front end and a node.js backend with express. I followed this guide https://levelup.gitconnected.com/how-to-render-react-app-using-express-server-in-node-js-a428ec4dfe2b to set up the bones of the app. To be honest I am not quite sure what code to include so I will include everything I think is necessary. The issue is every time I make a change, the terminal crashes and I am forced to restart the process.
In previous tutorials I set up the server on a different port then ran nodemon to update every time changes were made. I have watched 10+ hours of videos and have read countless articles on how to use node/express but I cant seem to get past the initial setup without something going completely wrong and having to try and find a new tutorial. I am newer to Node and very new to express so any constructive knowledge is appreciated. Thank you!
index.js
const express = require("express");
const app = express(); // create express app
// add middleware
const path = require("path");
// as the build folder will be created inside react-app folder, we are creating a path for the build folder located outside the server folder. must go first!!
app.use(express.static(path.join(__dirname, "..", "build")));
app.use(express.static("public"));
// start express server on port 5000
app.listen(5000, () => {
console.log("server started on port 5000");
});
package.json
{
"name": "react-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^1.3.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
"express": "^4.18.2",
"mongodb": "^5.0.1",
"mongoose": "^6.9.1",
"morgan": "^1.10.0",
"nodemon": "^2.0.20"
},
"scripts": {
"start-client": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"start": "yarn run build && (cd server && yarn start)"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
app.js. example code comment down is from the explanation on how to insert data using express.
import React from "react";
import axios from "axios";
import "./styles.css";
import DayContainer from './views/dayContainer/dayContainer'
import Header from './views/Header/header';
import Form from "./views/Form/form";
export default class App extends React.Component {
state = {
users: [],
};
componentDidMount() {
axios.get("/users.json").then((response) => {
this.setState({ users: response.data });
});
}
render() {
const { users } = this.state;
return (
<div className="App">
<Header/>
<div className='module-container'>
<DayContainer/>
<Form/>
</div>
{/* example code */}
<div>
<ul className="users">
{users.map((user) => (
<li className="user">
<p>
<strong>Name:</strong> {user.name}
</p>
<p>
<strong>Email:</strong> {user.email}
</p>
<p>
<strong>City:</strong> {user.address.city}
</p>
</li>
))}
</ul>
</div>
</div>
);
}
}
I have used multiple different tutorials using different methods of setting up express. I think this issue might stem from the fact that both the server and front end are using the same port but I could be wrong.
EDIT: adding server.json
{
"name": "express-static-serve",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "nodemon index.js"
},
"license": "MIT",
"dependencies": {
"express": "^4.18.2",
"nodemon": "^2.0.20"
}
}
Error :
Terminal exits with error code 2
Evey time I change something then refresh the app. I need to press ctrl + c to exit the process and then I get error code 2 and the terminal closes
That's a pretty convoluted way to set up react, and probably not what will want when you go to production. The best way is to have the react app use a proxy to redirect it to the main server. Here's how to do it: https://create-react-app.dev/docs/proxying-api-requests-in-development/
Basically you just add a "proxy" property to the react app's package.json and point to the URL of the node server. If that doesn't work you can configure the proxy manually (https://create-react-app.dev/docs/proxying-api-requests-in-development/#configuring-the-proxy-manually).
I've never understood why the developers of react made it so complicated as having to run two separate servers just to develop an app, when in production, it's only one server. But I've found it is one of the pain points for newcomers into the react world. Hopefully the instructions there will be of more help.
If you do this, you don't need two app.static entries in your server's index.js.

I cant import with jest in vue

im trying to learn testing but i get this problem. It seem that jest can not import modules. I have tried a lot of configurations but i couldn't solve it
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:
/home/alain-maza/Documentos/entrenamiento/vue/04-pokemon/node_modules/axios/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import axios from "axios";
| ^
2 |
3 | const pokemonApi = axios.create({
4 | baseURL: 'https://pokeapi.co/api/v2/pokemon'
this is my jest.config
module.exports = {
preset: '#vue/cli-plugin-unit-jest',
}
this is my babel.config
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset'
]
}
and my package.json
{
"name": "04-pokemon",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"test:unit": "vue-cli-service test:unit"
},
"dependencies": {
"axios": "^1.0.0",
"core-js": "^3.8.3",
"vue": "^3.2.13"
},
"devDependencies": {
"#babel/core": "^7.19.3",
"#babel/preset-env": "^7.19.4",
"#vue/cli-plugin-babel": "~5.0.0",
"#vue/cli-plugin-unit-jest": "~5.0.0",
"#vue/cli-service": "~5.0.0",
"#vue/test-utils": "^2.0.0-0",
"#vue/vue3-jest": "^27.0.0-alpha.1",
"babel-jest": "^27.5.1",
"jest": "^27.0.5"
}
}
heklpme please! i have trried a lot of things

Node js + TypeSc + Babel "Error: Cannot find module 'koa'"

I have cloned a demo . after installing koa,koa-router etc, I got an error. Here is my index.ts file
import Koa from "koa"
import Router from "koa-router"
import logger from "koa-logger"
import json from "koa-json"
const app = new Koa()
const router = new Router()
router.get("/",async(ctx: any,next: any)=>{
ctx.body = {
meg:"Hello world"
}
await next
})
app.use(logger())
app.use(json())
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000,()=>console.log("app is running at 3000"))
Here is my package.json
{
"name": "babel-typescript-sample",
"version": "0.7.2",
"license": "MIT",
"scripts": {
"type-check": "tsc --noEmit",
"type-check:watch": "npm run type-check -- --watch",
"build": "npm run build:types && npm run build:js",
"build:types": "tsc --emitDeclarationOnly",
"build:js": "babel src --out-dir lib --extensions \".ts,.tsx\" --source-maps inline"
},
"devDependencies": {
"#babel/cli": "^7.8.3",
"#babel/core": "^7.8.3",
"#babel/plugin-proposal-class-properties": "^7.8.3",
"#babel/preset-env": "^7.8.3",
"#babel/preset-typescript": "^7.8.3",
"#types/koa": "^2.11.3",
"typescript": "^3.7.5"
},
"dependencies": {
"koa": "^2.11.0",
"koa-bodyparser": "^4.3.0",
"koa-json": "^2.0.2",
"koa-logger": "^3.2.1",
"koa-router": "^8.0.8"
}
}
my file structure loos like:
/-------
-lib
-index.js
-index.d.ts
-node_modules
-src
-index.ts
Actually,before this ,when I run npm run build,I got error src/index.ts:2:20 - error TS2307: Cannot find module 'koa-router'. I write koa-router.d.ts myself, but I don't think it's a great idea, How do you guys resolve?
You have a few options:
Install koa-router typings with npm install --save-dev #types/koa-router.
Set moduleResolution inside tsconfig.json to node. See this for differences. Note that this option only works if the dependency has typings included. In this case, it does not, so first option would be more correct.
Edit paths (points to directory) or types (points to .d.ts) inside tsconfig.json to point to your typings. Yes, writing your typings ("by hand") for existing dependency is generally considered a bad idea, since it could update and therefore break your typings. If a dependency does not have typings, you can contribute to it by generating it using JSDoc, if it uses JavaScript.

Jest test fails at very first import statement (unexpected identifier) in create-react-native-app project

New to using jest and running into immediate test failure on an existing create-react-native-app project when trying to run npm test even though the code appears to work fine when run in the android studio AVD. Error in question looks like
➜ npm test
> spicex_react_native#0.1.0 test /path/to/project
> jest
PASS __tests__/example-test.js
FAIL ./App.test.js
● Test suite failed to run
/home/me/path/to/project/node_modules/tcomb-form-native/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import t from "./lib";
^
SyntaxError: Unexpected identifier
> 1 | import { PropTypes } from 'prop-types';
2 | import React from 'react';
3 | import { Alert, Button, ScrollView, StyleSheet, Text, View } from 'react-native';
4 | import Spinner from 'react-native-loading-spinner-overlay';
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:316:17)
at Object.<anonymous> (app/containers/path/to/some/component.js:1:1290)
Test Suites: 1 failed
Examining the component denoted by the component.js file in the android AVD, the screen renders without any errors or warnings. And the project's package.json looks like
{
"name": "spicex_react_native",
"version": "0.1.0",
"private": true,
"devDependencies": {
"eslint": "^5.3.0",
"eslint-config-standard": "^11.0.0",
"eslint-plugin-import": "^2.13.0",
"eslint-plugin-node": "^7.0.1",
"eslint-plugin-promise": "^3.8.0",
"eslint-plugin-react": "^7.10.0",
"eslint-plugin-react-redux": "^2.3.0",
"eslint-plugin-standard": "^3.1.0",
"jest-expo": "~27.0.0",
"react-native-scripts": "^1.14.1",
"react-test-renderer": "16.3.1"
},
"main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
"scripts": {
"start": "react-native-scripts start",
"eject": "react-native-scripts eject",
"android": "react-native-scripts android",
"ios": "react-native-scripts ios",
"test": "jest"
},
"jest": {
"preset": "jest-expo"
},
Was not totally sure how could debug properly from just the docs (https://jestjs.io/docs/en/tutorial-react-native.html#setup). If anyone knows what could be going on here, advice or suggestions would be appreciated.

Testing React components with Mocha: unexpected token

I have my React components all fleshed out, and I wanted to learn how to test these components properly with Mocha + chai. I have these configurations for my package.json (relevant ones):
"scripts": {
"start": "http-server",
"build": "watchify main.js -t babelify -o bundle.js",
"test": "./node_modules/mocha/bin/mocha --compilers js:babel-core/register test/test*.js"
},
"devDependencies": {
"babel": "^5.6.23",
"babelify": "^6.1.3",
"browserify": "^11.0.0",
"chai": "^3.5.0",
"jsdom": "^9.8.3",
"mocha": "^3.2.0",
"react-addons-test-utils": "^15.4.1"
},
"babel": {
"presets": [
"es2015"
]
}
I have Skill.js:
import React from 'react';
import _ from 'underscore';
export default class Skills extends React.Component {
render() {
return (
<div>
<h1>T E S T</h1>
</div>
)
}
}
along with a test.js in a folder called test:
import React from 'react';
import { expect, assert } from 'chai';
import Skills from '../src/components/Skills.js';
I'm receiving an unexpected token error when I run npm test.
What's the console complaining about? Why is the <div> tag not valid?
I had a similar issue and at first I thought I did not import React from 'react';.
Next I found out that I did not add --require ./test/test_helper.js
And last but then after still not working, it dawned on me that I did not restart node. That fixed it for me.
You need to install babel-preset-es2015 before using it
npm install --save-dev babel-preset-es2015

Resources