Test config for AVA + React-Native - javascript

I try to test my react-native application using AVA and the babel-preset-react-native
My config looks like this:
"scripts": {
"test": "ava"
},
"ava": {
"files": [
"src/**/__tests__/*.js"
],
"failFast": true,
"require": [
"react-native-mock/mock.js",
"babel-register"
],
"babel": {
"presets": [
"react-native"
]
}
},
"devDependencies": {
"ava": "^0.13.0",
"babel-preset-react-native": "^1.2.4",
"babel-register": "~6.4.3",
"react-native-mock": "0.0.6"
}
…and fails like this:
/Users/zoon/Projets/xxxxx/node_modules/babel-register/node_modules/babel-core/lib/transformation/file/index.js:556
throw err;
^
SyntaxError: /Users/zoon/Projets/xxxxx/src/reducers/env.js: Unexpected token (12:8)
10 | case types.RECEIVE_CHANGE_ENV:
11 | return {
> 12 | ...state,
| ^
13 | current: Environments[action.env]
14 | };
15 | default:
If I export this babel config in a .babelrc file and use "babel": "inherit" in my AVA config, it fails in an other way:
/Users/zoon/Projets/xxxxx/node_modules/lodash-es/lodash.js:10
export { default as add } from './add';
^^^^^^
SyntaxError: Unexpected token export
I can't understand how to correctly configure this. I've tried Mocha, encountered the same problems.

babel-register ignores node_modules by default. You can set ignore:false in your .babelrc to disable that behavior. You could (probably should) also specify a more limited regular expression to avoid processing everything in node_modules.
See the docs: https://babeljs.io/docs/usage/require/
Your complete config should probably look something like this:
.babelrc
{
"presets": ["react-native"],
"ignore": false
}
package.json
{
"ava": {
"babel": "inherit"
}
}

Related

The error "SyntaxError: Cannot use import statement outside a module" appears when I try to run npm test in my react application

I have spent more than 2 days to research to solve the problem regarding testing library and jest in my react application but it does not work.
The error appearing in my terminal each time I run npm test looks like below:
FAIL src/App.test.jsx
● 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/thanhnhan/Desktop/capstone-frontend/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
3 | import LoginPage from "./pages/LoginPage/LoginPage";
4 | import { useEffect, useState } from "react";
> 5 | import axios from "axios";
| ^
6 | import HomePage from "./pages/HomePage/HomePage";
7 | import HeaderComponent from "./components/HeaderPage/HeaderComponent";
8 | import SideMenu from "./components/SideMenu/SideMenu";
at Runtime.createScriptFromCode (node_modules/react-scripts/node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/App.jsx:5:1)
at Object.<anonymous> (src/App.test.jsx:2:1)
at TestScheduler.scheduleTests (node_modules/react-scripts/node_modules/#jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/react-scripts/node_modules/#jest/core/build/runJest.js:404:19)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.243 s
Ran all test suites related to changed files.
Watch Usage: Press w to show more.
My test file is the App.test.jsx:
import { render } from "#testing-library/react";
import App from "./App";
describe("<App />", () => {
it("should match snapshot", () => {
const snapshot = render(<App />);
expect(snapshot).toMatchSnapshot();
});
});
My package.json looks like this:
{
"name": "capstone-frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.10.5",
"#emotion/styled": "^11.10.5",
"#mui/material": "^5.11.4",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^1.2.0",
"chart.js": "^4.0.1",
"faker": "^5.5.3",
"fitness-calculator": "^1.1.0",
"framer-motion": "^7.6.19",
"js-sha256": "^0.9.0",
"react": "^18.2.0",
"react-chartjs-2": "^5.0.1",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.4",
"react-scripts": "5.0.1",
"react-slick": "^0.29.0",
"sass": "^1.56.1",
"slick-carousel": "^1.8.1",
"uuid": "^9.0.0",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"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"
]
},
"devDependencies": {
"#babel/core": "^7.20.12",
"#babel/plugin-transform-modules-commonjs": "^7.20.11",
"#babel/preset-env": "^7.20.2",
"babel-jest": "^29.3.1",
"jest": "^29.3.1"
}
}
After researching, I know that JestJS can not read some syntaxes in my App.jsx, so I need to use babel. Here is what my babel.config.js file looks like:
module.exports = {
presets: ["#babel/preset-env", "#babel/preset-react"],
env: {
test: {
plugins: ["#babel/plugin-transform-runtime"],
},
},
};
I have also tried using .babelrc file but it does not work. I am very stressed now and I hope that someone can help me figure this out. Thank you so so much for your help.
I don't have an answer for you for now, but hate to hear you're stressed about your issue.
I have had issues in the past with mixing import, export, with modules.exports and require statements. Using babel I was able to "do it all" though. But as of late have been trying to standardize using only import and export statements. Here is my babel.config.js. I am also using webpack
module.exports = {
presets: [
["#babel/preset-env", {
useBuiltIns: "entry",
corejs: {
version: 3,
}
}],
"#babel/react"
],
plugins: [
["#babel/plugin-transform-regenerator"],
["#babel/plugin-transform-runtime", {
corejs: {
version: 3
},
helpers: true
}],
// ["#babel/plugin-transform-runtime", {
// corejs: {
// version: 3
// },
// }],
// Stage 0
"#babel/plugin-proposal-function-bind",
// Stage 1
"#babel/plugin-proposal-export-default-from",
"#babel/plugin-proposal-logical-assignment-operators",
["#babel/plugin-proposal-optional-chaining", { "loose": false }],
["#babel/plugin-proposal-pipeline-operator", { "proposal": "minimal" }],
["#babel/plugin-proposal-nullish-coalescing-operator", { "loose": false }],
"#babel/plugin-proposal-do-expressions",
// Stage 2
["#babel/plugin-proposal-decorators", { "legacy": true }],
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-throw-expressions",
// Stage 3
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
["#babel/plugin-proposal-class-properties", { "loose": false }],
"#babel/plugin-proposal-json-strings"
]
}
it seems that you missed babel-jest module:
https://jestjs.io/docs/28.x/getting-started#using-babel
[UPDATES]
Ok, it seems you use CRA so there is not need to install separately that module.
I have checked the error log and it seems that import statement does not work properly only in your node_module (error happens in axios module).
By default Jest does not transform files from node_modules.
Please check transformIgnorePatterns property of jest config and e.g
"jest": {
"transformIgnorePatterns": ["node_modules/(?!axios)/"]
},
see https://github.com/axios/axios/issues/5101
or event better=) - https://github.com/axios/axios/issues/5101#issuecomment-1307878899
"type":"module",
Add this to your package.json to use ES6 modules .

set absolute path for jest in react project

I have followed this document and set an absolute path across the project. But when I run test case it gives me following error
Your application tried to access assets, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.
Required package: assets (via "assets\icons")
Required by: E:\Project\src\components\LayoutContainer\
Require stack:
src/components/LayoutContainer/index.jsx
src/components/LayoutContainer/__test__/index.spec.js
27286 | enumerable: false
27287 | };
> 27288 | return Object.defineProperties(new Error(message), {
| ^
27289 | code: { ...propertySpec,
27290 | value: code
27291 | },
at internalTools_makeError (.pnp.js:27288:34)
at resolveToUnqualified (.pnp.js:28247:23)
at resolveRequest (.pnp.js:28345:29)
at Object.resolveRequest (.pnp.js:28423:26)
My Package.json for jest configuration is as follow
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}",
"!src/components/**/*.{js,jsx}",
"!<rootDir>/node_modules/",
"!<rootDir>/path/to/dir/",
"!src/**/*.css",
"!src/setUpTests.js",
"!src/index.jsx"
],
"coverageThreshold": {
"global": {
"branches": 90,
"functions": 90,
"lines": 90,
"statements": 90
}
},
"snapshotSerializers": [
"enzyme-to-json/serializer"
]
},
I tried to follow many open solutions. But none are working for me
My jsonconfig.json file
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
I added the following configuration as part of craco file and worked for me
module.exports = {
jest: {
configure: {
moduleNameMapper: {
// Jest module mapper which will detect our absolute imports.
'^assets(.*)$': '<rootDir>/src/assets$1',
'^pages(.*)$': '<rootDir>/src/pages$1',
'^config(.*)$': '<rootDir>/src/config$1',
'^navigation(.*)$': '<rootDir>/src/navigation$1',
'^utils(.*)$': '<rootDir>/src/utils$1',
'^components(.*)$': '<rootDir>/src/components$1',
'^services(.*)$': '<rootDir>/src/services$1',
// Another example for using a wildcard character
'^~(.*)$': '<rootDir>/src$1'
}
}
}
}
reference - https://resir014.xyz/posts/2019/03/13/using-typescript-absolute-paths-in-cra-20

Exported function is undefined

I'm facing an issue with my Mocha tests in Typescript, I fear it is related to Babel, but I am really not sure what's happening.
Essentially, I have a function that is being exported in a file
// src/my-ts-lib/tests/components/factoryMocks/componentConfigMocks.ts
...
export function getRandomConfig(type?: string): ComponentConfig {
const randomComponentType = type || randomType();
return {
type: randomComponentType,
config: configLibrary[randomComponentType]
}
}
And being imported in another, which is being called by a test:
// src/my-ts-lib/tests/components/RouteComponent/mocks/routeMocks.ts
...
import { getRandomConfig } from '../../factoryMocks/componentConfigMocks';
..
export const getSingleRouteConfigMock = (componentType?: string): RouteProps => {
const defaultComponentType = 'PageLayout';
return {
childComponent: {
type: componentType || defaultComponentType,
config: getRandomConfig(componentType || defaultComponentType)
},
pageName: randomString(),
path: randomString(),
};
};
...
When running the tests, I get the following error:
RouteCompnent/mocks/routeMocks.ts:10
config: getRandomConfig(componentType || defaultComponentType),
^
TypeError: componentConfigMocks_1.getRandomConfig is not a function
at Object.exports.getSingleRouteConfigMock (/Users/.../routeMocks.ts:10:44)
If I comment the call and console.log(getRandomConfig) I can see that it is undefined. I do not know why this is happening. What's even weirder is that, in subsequent tests that call getSingleRouteConfigMock, this same console.log correctly outputs the function, meaning that it has been exported then.
I've fiddled around with Babel, Mocha, and Typescript configs but have had no success.
Here's the Babel config:
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
The Mocha config:
mocha.opts
--require ts-node/register
--watch-extensions ts tsx
--require source-map-support/register
--recursive
--require #babel/register
--require #babel/polyfill
src/**/*.spec.**
And the Typescript config:
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": false,
"module": "commonjs",
"target": "es6",
"jsx": "react"
},
"include": [
"./src/**/*"
],
"exclude": [
"./src/**/*.spec.ts",
"./src/my-ts-lib/components/**/*.spec.tsx",
"./src/my-ts-lib/test-helpers/*"
],
}
And the relevant sections of the package.json
...
"dependencies": {
...
"#babel/polyfill": "7.2.x",
...
},
"devDependencies": {
"#babel/core": "7.2.x",
"#babel/preset-env": "7.2.x",
"#babel/preset-react": "7.0.x",
"#babel/register": "7.0.x",
"babel-loader": "8.x",
"mocha": "3.2.x",
...
}
I found out I have a circular dependency. That's why this was not working.
Another possible cause for this symptom is that the function is actually missing in the module when you use a bundler like Parcel in production mode and it removes unused items (that particular issue discussed at Empty Javascript File When Building With Parcel JS 2 ). Check the compiled module file and make sure that the name exists.

Jest tests crashing due to ES6/Es.next Syntax

I'm trying to do some simple snapshot testing with jest and enzyme—moving to react-testing-library—for some react components that I am building.
When I run my tests the output contains a number of errors pointing to ES6/7 class properties.
My assumption was that I was missing babel-jest. I have followed the instructions to set that up but I am still receiving a number of errors from different components referring to a missing the babel transform...
See below:
Example Test:
import React from 'react';
import { render } from 'react-testing-library';
import HRWrapper from '.';
test('<HRWrapper> snapshot', () => {
const { container } = render(<HRWrapper>P.Body AaBbCc</HRWrapper>);
expect(container.firstChild).toMatchSnapshot();
});
Example Error:
● Test suite failed to run
.../packages/Tooltip/src/index.js: Missing class properties transform.
126 |
127 | class ToolTip extends React.Component {
> 128 | state = {
| ^
129 | active: false,
130 | style: {}
131 | }
Here is my configuration:
package.json:
{
...
"scripts": {
"postinstall": "npm run bootstrap",
"bootstrap": "lerna bootstrap",
"build": "lerna exec -- node ../../scripts/build.js",
"clean": "lerna clean",
"predev": "npm run alias",
"dev": "NODE_ENV=development start-storybook -p 9001 -c .storybook",
"docs": "for f in packages/*; do react-doc-generator $f/src -o $f/docs/README.md -e [*.story.js]; done",
"publish": "lerna --no-verify-registry publish",
"start": "npm run dev",
"test": "jest --json --outputFile=.jest-test-results.json",
"test:update": "jest --updateSnapshot",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"lint": "eslint .",
"fix": "eslint --fix",
"alias": "node scripts/alias.js"
},
"repository": {
"type": "git",
...
.babelrc:
{
"presets": [
"stage-1",
"react",
[
"env",
{
"modules": false
}
]
],
"plugins": ["transform-class-properties"],
"env": {
"test": {
"presets": ["env", "react"],
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
jest.config.js:
module.exports = {
"setupTestFrameworkScriptFile": "<rootDir>/config/setup-test.js",
"moduleNameMapper": {
[`#myLibrary/(.*)$`]: "<rootDir>/packages/$1/src"
},
"transform": {
"^.+\\.jsx?$": "babel-jest"
},
};
setup-test.js:
// this is the jest setupTestFrameworkScriptFile
/*
* use mocked classNames instead of unique hashed className generated by
* styled-components for snapshot testing
*/
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'jest-styled-components';
configure({ adapter: new Adapter() });
// here we set up a fake localStorage because jsdom doesn't support it
// https://github.com/tmpvar/jsdom/issues/1137
if (!window.localStorage) {
window.localStorage = {};
Object.assign(window.localStorage, {
removeItem: function removeItem(key) {
delete this[key];
}.bind(window.localStorage),
setItem: function setItem(key, val) {
this[key] = String(val);
}.bind(window.localStorage),
getItem: function getItem(key) {
return this[key];
}.bind(window.localStorage),
});
}
It's possible you also need stage-2 or stage-0.
See: https://github.com/tc39/proposals
Also remember that plugins are applied BEFORE presets, and presets are applied in order of last to first.
My colleague spotted the issue, one of those obvious ones staring me in the face...
transform-class-properties was missing from the plugins in my test environment configuration in my .babelrc.
I made the following changes and it now works properly.
.babelrc:
{
"presets": [
"stage-1",
"react",
[
"env",
{
"modules": false
}
]
],
"plugins": ["transform-class-properties"],
"env": {
"test": {
"presets": ["env", "react"],
"plugins": ["transform-class-properties", "transform-es2015-modules-commonjs"]
}
}

Syntax error in ReactJS

I'm starting to learn ReactJS and I'm following instructions in a book on getting started. My directory structure looks like this:
app/App.js
node_modules
index.html
package.json
webpack.config.js
I think that the culprit of the problem is this error message from CLI:
ERROR in ./app/App.js
Module build failed: SyntaxError: c:/code/pro-react/my-app/app/App.js: Unexpected token (6:6)
4 | render() {
5 | return (
> 6 | <h1>Hello World</h1>
| ^
7 | );
8 | }
9 | }
The contents of App.js are:
import React from 'react';
class Hello extends React.Component {
render() {
return (
<h1>Hello World</h1>
);
}
}
React.render(<Hello />, document.getElementById('root'));
Here is the contents of package.json:
{
"name": "my-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node_modules/.bin/webpack-dev-server --progress",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.4.5",
"babel-loader": "^6.2.1",
"webpack": "^1.12.11",
"webpack-dev-server": "^1.14.1"
},
"dependencies": {
"react": "^0.14.6"
}
}
And the contents of webpack.config.js are:
module.exports = {
entry: __dirname + "/app/App.js",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel'
}]
}
};
I launch the application from CLI with the command:
npm start
And when I go to http://localhost:8080 in Dev Tools there is an error message:
GET http://localhost:8080/bundle.js 404 (Not Found)
But as I said, I think that the culprit is that it doesn't like the syntax so it doesn't make the bundle.js file. Please let me know what I'm doing wrong.
I think it happens because you are using babel-6 without babel presets, in this case you need babel-preset-es2015 and babel-preset-react.,
# For ES6/ES2015 support
npm install babel-preset-es2015 --save-dev
# Fot JSX support
npm install babel-preset-react --save-dev
then change webpack config
{
test: /\.jsx?$/,
loader: 'babel',
query: {
presets: ['es2015', 'react'],
}
}
or instead of using query you can create .babelrc file with content
{
"presets": ["es2015", "react"]
}
also you need install react-dom and use ReactDOM.render instaed or React.render

Categories

Resources