I Started learning THREEJS but every time I execute npm run dev the following error comes up and I can't figure out what is wrong with my npm . node v18.7.0
I am learning this course from Threejs journey and the starter pack they gave and told me to run the commands in the terminal I am encountering the error mentioned below
I have no idea how to fix this.
Error
[webpack-cli] Failed to load 'D:\3js\l2\04-webpack\bundler\webpack.dev.js' config
[webpack-cli] Error [ERR_REQUIRE_ESM]: require() of ES Module D:\3js\l2\04-webpack\node_modules\internal-ip\index.js from D:\3js\l2\04-webpack\bundler\webpack.dev.js not supported.
Instead change the require of index.js in D:\3js\l2\04-webpack\bundler\webpack.dev.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (D:\3js\l2\04-webpack\bundler\webpack.dev.js:4:12)
at async Promise.all (index 0)
at async WebpackCLI.tryRequireThenImport (D:\3js\l2\04-webpack\node_modules\webpack-cli\lib\webpack-cli.js:254:18)
at async WebpackCLI.createCompiler (D:\3js\l2\04-webpack\node_modules\webpack-cli\lib\webpack-cli.js:2185:18)
at async Command.<anonymous> (D:\3js\l2\04-webpack\node_modules\#webpack-cli\serve\lib\index.js:98:30)
at async Promise.all (index 1)
at async Command.<anonymous> (D:\3js\l2\04-webpack\node_modules\webpack-cli\lib\webpack-cli.js:1672:7) {
code: 'ERR_REQUIRE_ESM'
}
package.json
{
"repository": "#",
"license": "UNLICENSED",
"scripts": {
"build": "webpack --config ./bundler/webpack.prod.js",
"dev": "webpack serve --config ./bundler/webpack.dev.js"
},
"dependencies": {
"#babel/core": "^7.15.8",
"#babel/preset-env": "^7.15.8",
"babel-loader": "^8.2.3",
"clean-webpack-plugin": "^4.0.0",
"copy-webpack-plugin": "^9.0.1",
"css-loader": "^6.5.0",
"file-loader": "^6.2.0",
"html-loader": "^3.0.0",
"html-webpack-plugin": "^5.5.0",
"internal-ip": "^7.0.0",
"mini-css-extract-plugin": "^2.4.3",
"portfinder-sync": "0.0.2",
"raw-loader": "^4.0.2",
"style-loader": "^3.3.1",
"three": "^0.134.0",
"webpack": "^5.60.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.4.0",
"webpack-merge": "^5.8.0"
}
}
webpack.dev.js
const path = require('path')
const { merge } = require('webpack-merge')
const commonConfiguration = require('./webpack.common.js')
const ip = require('internal-ip')
const portFinderSync = require('portfinder-sync')
const infoColor = (_message) =>
{
return `\u001b[1m\u001b[34m${_message}\u001b[39m\u001b[22m`
}
module.exports = merge(
commonConfiguration,
{
stats: 'errors-warnings',
mode: 'development',
devServer:
{
host: 'local-ip',
port: portFinderSync.getPort(8080),
open: true,
https: false,
allowedHosts: 'all',
hot: false,
watchFiles: ['src/**', 'static/**'],
static:
{
watch: true,
directory: path.join(__dirname, '../static')
},
client:
{
logging: 'none',
overlay: true,
progress: false
},
onAfterSetupMiddleware: function(devServer)
{
const port = devServer.options.port
const https = devServer.options.https ? 's' : ''
const localIp = ip.v4.sync()
const domain1 = `http${https}://${localIp}:${port}`
const domain2 = `http${https}://localhost:${port}`
console.log(`Project running at:\n - ${infoColor(domain1)}\n - ${infoColor(domain2)}`)
}
}
}
)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
import path from 'path'
import { merge } from 'webpack-merge'
import commonConfiguration from './webpack.common.js'
import ip from 'internal-ip'
import portFinderSync from 'portfinder-sync'
Related
I am getting this error for the past hours and i have not been able to resolve it. I have tried all the solutions online including uninstalling aslant globally and in the project and installing it again. Unfortunately the most common answer does not really apply in my case since my package.json file does not really have that file structure.
Running command: npm --prefix "$RESOURCE_DIR" run lint
> lint
> eslint .
/Users/KingdomMac/Downloads/ermnl-dashboard-master/functions/index.js
22:71 error Parsing error: Unexpected token =>
✖ 1 problem (1 error, 0 warnings)
Error: functions predeploy error: Command terminated with non-zero exit code1
My package.json file
{
"name": "vue-white-dashboard",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.35",
"#fortawesome/free-brands-svg-icons": "^5.15.3",
"#fortawesome/free-regular-svg-icons": "^5.15.3",
"#fortawesome/free-solid-svg-icons": "^5.15.3",
"#fortawesome/vue-fontawesome": "^2.0.2",
"axios": "^0.21.1",
"chart.js": "^2.8.0",
"core-js": "^2.6.5",
"firebase": "^8.6.8",
"node-sass": "^4.9.0",
"vue": "^2.6.10",
"vue-chartjs": "^3.4.2",
"vue-click-outside": "^1.0.7",
"vue-clickaway": "^2.2.2",
"vue-github-buttons": "^3.1.0",
"vue-i18n": "^8.14.1",
"vue-router": "^3.0.3",
"vue-social-sharing": "^2.4.6",
"vue2-transitions": "^0.3.0",
"vuetify": "^2.4.0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "^3.11.0",
"#vue/cli-plugin-eslint": "^3.1.1",
"#vue/cli-service": "^3.5.3",
"#vue/eslint-config-prettier": "^5.0.0",
"babel-eslint": "^10.0.1",
"eslint": "^8.1.0",
"eslint-config-google": "^0.14.0",
"eslint-plugin-prettier": "^3.1.0",
"eslint-plugin-vue": "^7.20.0",
"prettier": "^1.18.2",
"sass": "~1.32",
"sass-loader": "^10.0.0",
"vue-cli-plugin-vuetify": "~2.4.1",
"vue-template-compiler": "^2.6.10",
"vuetify-loader": "^1.7.0"
}
}
Also my .eslintrc.js file
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": "plugin:vue/essential",
"parserOptions": {
"ecmaVersion": 13
},
"plugins": [
"vue"
],
"rules": {
}
};
And my index.js file
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
// exports.addAdminRole = functions.https.onCall((data, context) => {
// // Get user and add custom claim (admin)
// const customClaims = {
// admin: true,
// };
// return admin.auth().getUserByEmail(data.email).then((user) => {
// return admin.auth().setCustomUserClaims(user.uid, customClaims);
// }).then((authUser) => {
// return {
// message: `Success! ${data.email} has been made an admin.`,
// };
// }).catch((error) => {
// return error;
// });
// });
exports.addUserRole = functions.auth.user().onCreate(async (authUser) => {
if (authUser.email) {
const customClaims = {
admin: true,
};
try {
let _ = await admin.auth().setCustomUserClaims(authUser.uid, customClaims);
return db.collection("roles").doc(authUser.uid).set({
email: authUser.email,
role: customClaims,
});
} catch (error) {
console.log(error);
}
}
});
exports.setUserRole = functions.https.onCall(async (data, context) => {
if (!context.auth.token.admin) return
try {
let _ = await admin.auth().setCustomUserClaims(data.uid, data.role)
return db.collection("roles").doc(data.uid).update({
role: data.role
})
} catch (error) {
console.log(error)
}
});
try changing "lint": "eslint ." to "lint": "eslint ", in your package.json
I have gone in so many circles since development, I'm now a bit lost and the code is a mess. This is
my first node project (outside a framework) and I'm starting to wish I'd used PHP.Anyway, here is the webpack.common.js file.
const path = require('path');
require("babel-polyfill");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
app: ['babel-polyfill','./src/index.js'],
},
plugins: [
new HtmlWebpackPlugin({
title: 'Production',
filename: 'index.html',
template: './src/index.html',
}),
],
output: {
publicPath: '/',
filename: 'js/bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use:{
loader: 'babel-loader'
}
},
{
test: /\.css$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader'],
},
]
},
};
When I push to Heroku master I set NPM_CONFIG_PRODUCTION is 'false' so that dev dependencies also get
loaded. Here is the package.json so you know what I'm using and what I've tried to some extent.
{
"name": "stock",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server --mode development --open",
"start": "node backendindex.js",
"heroku-postbuild": "webpack -p"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.7.5",
"#babel/plugin-transform-runtime": "^7.8.3",
"#babel/preset-env": "^7.7.6",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.6",
"babel-plugin-transform-regenerator": "^6.26.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"css-loader": "^3.4.0",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^1.0.2",
"webpack": "^4.41.3",
"webpack-dev-server": "^3.10.0",
"webpack-merge": "^4.2.2"
},
"dependencies": {
"#babel/runtime": "^7.8.3",
"axios": "^0.19.0",
"bootstrap": "^4.4.1",
"core-js": "^3.6.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"helmet-csp": "^2.9.4",
"jquery": "^1.12.4",
"mysql": "^2.17.1",
"popper.js": "^1.16.0",
"regenerator-runtime": "^0.13.3",
"serve-favicon": "^2.5.0",
"webpack-cli": "^3.3.10"
},
"engines": {
"node": "12.13.1",
"npm": "6.12.1"
}
}
The next bit I'm a bit unsure of when live as I have not got to test it yet, but it seems about
right. This is a search class for the db calls.
import axios from 'axios';
"use strict";
export default class Router{
constructor(query){
this.query = query;
}
async getResults(){
try{
const res = await axios(`https://stockapp.herokuapp.com/api/stockapi/${this.query}`);
this.result = res;
//console.log(this.result);
}catch(error){
alert(error);
}
}
}
Finally here are my express settings.
app.use(express.static(__dirname + '/dist'));
app.use(express.json());
app.use('/api/stockapi', apiRouter);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port: ${PORT}`);
});
app.get('*', (req, res) => {
const index = path.join(__dirname, 'dist', 'index.html');
res.sendFile(index);
});
So once pushed to Heroku the index.html is served and looks OK, then when I make a call to the DB as
soon as it wants to return regenerator runtime async it gives me this error. I have tried everything!
Help me OB1 you're my only hope!!!
It transpires that I just needed to run a production build using npm run build.
I got this environment working now but for anyone using Heroku I think the single most important thing is to run 'heroku logs --tail' and check for errors. It is incredibly helpful for debugging!!
I am trying to build a custom webpack configuration for a complex project. While building I have observed that webpack is generating separate JS file when I import babel-runtime/core-js/json/stringify. Can someone help me understand what's happening here and why webpack is generating a separate JS file.
package.json
{
"name": "react-boilerplate",
"version": "1.0.0",
"description": "A boilerplate for large scale react apps",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --mode development",
"build": "sh -ac 'webpack --mode production ${DEPLOY_TARGET:+--env.target $DEPLOY_TARGET}'",
"build:production": "DEPLOY_TARGET='production' yarn build",
"build:staging": "DEPLOY_TARGET='staging' yarn build"
},
"devDependencies": {
"#babel/core": "^7.6.4",
"#babel/plugin-proposal-class-properties": "^7.5.5",
"#babel/preset-env": "^7.6.3",
"#babel/preset-react": "^7.6.3",
"#typescript-eslint/eslint-plugin": "2.x",
"#typescript-eslint/parser": "2.x",
"babel-eslint": "10.x",
"babel-loader": "^8.0.6",
"babel-preset-react-app": "^9.0.2",
"clean-webpack-plugin": "^3.0.0",
"compression-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^5.0.4",
"dotenv": "^8.2.0",
"eslint": "6.x",
"eslint-config-react-app": "^5.0.2",
"eslint-loader": "^3.0.2",
"eslint-plugin-flowtype": "3.x",
"eslint-plugin-import": "2.x",
"eslint-plugin-jsx-a11y": "6.x",
"eslint-plugin-react": "7.x",
"eslint-plugin-react-hooks": "1.x",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^3.2.0",
"react-hot-loader": "^4.12.15",
"stylelint": "^11.1.1",
"stylelint-config-standard": "^19.0.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-custom-processor-loader": "^0.6.0",
"stylelint-processor-styled-components": "^1.8.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.2",
"webpack-merge": "^4.2.2",
"workbox-webpack-plugin": "^4.3.1"
},
"dependencies": {
"lodash": "^4.17.15",
"react": "^16.10.2",
"react-dom": "^16.10.2",
"react-router-dom": "^5.1.2",
},
"peerDependencies": {
"stylelint": "^11.1.1"
}
}
webpack.config.js
const { DefinePlugin } = require('webpack');
const path = require('path');
// Webpack plugins
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWepackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { rootDir } = require('./utils');
const {
entryPath,
getEnvJson,
htmlTemplatePath,
outputDir,
publicDir,
sourceDir,
} = require('./utils');
module.exports = env => ({
// Configure's our app entry points
entry: {
main: entryPath,
},
// Configure's loaders to let webpact know how different extension should be
// loaded when bundling
module: {
rules: [
// Configure's babel loader for transpiling javascript, eslint loader
// for linting javascript, stylelint loader for css linting
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
'babel-loader',
{
loader: 'stylelint-custom-processor-loader',
options: {
configPath: path.resolve(rootDir, '.stylelintrc.js'),
},
},
'eslint-loader',
]
},
// Configure's loaders for images
{
test: /.(png|jpg|jpeg|svg|gif)/,
use: 'file-loader'
},
]
},
// Configure's destination for the bundled code
output: {
path: outputDir,
},
// Configure's additions plugins to be used by webpack
// Order of plugins is important
plugins: [
// Removes all the contents of output folder(but not the folder itself)
// before every webpack build
new CleanWebpackPlugin(),
// Copies all contents of public folder as it is excluding index.html file
new CopyWepackPlugin([
{
from: publicDir,
to: outputDir,
ignore: ['index.html']
}
]),
// Injects target specific enviroment variables
new DefinePlugin({
'process.env': getEnvJson(env.target)
}),
// Uses `public/index.html` and creates a `index.html` file for the app
// by injecting the generated bundles javascript files
new HtmlWebpackPlugin({
template: htmlTemplatePath
}),
],
// Configure's custom behavior for how modules are resolved by webpack
resolve: {
modules: [sourceDir, 'node_modules']
}
});
.babelrc
{
"presets": ["react-app"]
}
That is because of your entryPath.
module.exports = {
entry: {
bundle1: '.src/fileForBundle1.js',
bundle2: '.src/fileForBundle2.js'
},
This would generate two bundles.
Make sure entryPath is not an object of multiple values.
Issue was with the file-loader regex which was incorrectly configured and which resulted in matching babel-runtime/core-js/json/stringify. So file-loader was being used to load it.
I am trying to develop a custom reporter for mocha output that will be used with protractor. I have developed a good deal of the reporter and if I use the "--reporter" command line argument it works fine. However if I try to specify it in mocharc, or more importantly reporterOptions within the protractor configuration file it can't seem to find the package. Is the command line reporter flag the only way to specify a local/custom reporter? If not, how are you supposed to specify it outside of the command line?
.babelrc:
require:
- '#babel/polyfill'
- '#babel/register'
reporter: './mocha-reporter'
spec: '_src/js/tests/unit/**/*.spec.js'
package.json:
{
"name": "box",
"version": "1.0.0",
"description": "boom!",
"main": "index.js",
"scripts": {
"mocha": "mocha",
"mocha-custom": "mocha -O outputDir=_src/js/tests/reports,testDir=_src/js/tests/unit --reporter mocha-reporter",
"mochawesonme": "mocha --reporter mochawesome --reporter-options reportDir=_src/js/tests/reports,reportFilename=PCMS_unit_test_results",
"check-types": "tsc",
"clean-selenium": "webdriver-manager clean",
"update-selenium": "webdriver-manager update --standalone --versions.standalone=3.8.0",
"start-selenium": "webdriver-manager start --versions.standalone=3.8.0",
"integration-tests": "protractor protractor.conf.js"
},
"devDependencies": {
"#babel/cli": "~7.4.3",
"#babel/core": "~7.4.3",
"#babel/plugin-proposal-class-properties": "7.4.0",
"#babel/plugin-proposal-object-rest-spread": "~7.4.3",
"#babel/plugin-transform-destructuring": "~7.4.3",
"#babel/polyfill": "~7.4.3",
"#babel/preset-env": "~7.4.3",
"#babel/preset-typescript": "~7.3.3",
"#babel/register": "~7.4.0",
"#fortawesome/fontawesome-free": "5.8.1",
"#types/bluebird": "3.5.26",
"#types/jquery": "3.3.29",
"#types/knockout": "~3.4.65",
"#typescript-eslint/eslint-plugin": "~1.7.0",
"#typescript-eslint/parser": "~1.7.0",
"appcache-webpack-plugin": "~1.4.0",
"autoprefixer": "~9.5.1",
"babel-loader": "~8.0.5",
"chai": "~4.2.0",
"chai-as-promised": "7.1.1",
"copy-webpack-plugin": "~5.0.3",
"css-loader": "~2.1.1",
"eslint": "~5.16.0",
"eslint-config-airbnb-base": "~13.1.0",
"eslint-config-airbnb-typescript": "~3.0.0",
"eslint-plugin-import": "~2.17.2",
"file-loader": "~3.0.1",
"html-loader": "~0.5.5",
"html-webpack-plugin": "3.2.0",
"js-yaml": "~3.13.1",
"json-loader": "~0.5.7",
"jszip": "~3.2.1",
"karma": "~4.1.0",
"karma-chai": "~0.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-firefox-launcher": "~1.1.0",
"karma-mocha": "~1.3.0",
"karma-sinon": "~1.0.5",
"karma-webpack": "~3.0.5",
"mini-css-extract-plugin": "~0.6.0",
"mocha": "~6.1.4",
"mocha-reporter": "file:mocha-reporter",
"mochawesome": "~3.1.2",
"mochawesome-report-generator": "3.1.5",
"mochawesome-screenshots": "1.6.0",
"node-sass": "^4.12.0",
"popper.js": "~1.15.0",
"postcss-loader": "~3.0.0",
"protractor": "5.4.2",
"protractor-image-comparison": "3.1.0",
"sass-loader": "~7.1.0",
"sinon": "~7.3.2",
"style-loader": "~0.23.1",
"typescript": "~3.4.5",
"url-loader": "~1.1.2",
"webpack": "~4.30.0",
"webpack-cli": "~3.3.1",
"webpack-dev-server": "~3.3.1"
},
"dependencies": {
"bluebird": "~3.5.4",
"bootstrap": "3.3.7",
"d3": "~5.9.2",
"isomorphic-fetch": "2.2.1",
"jquery": "^3.4.0",
"jquery-ui": "~1.12.1",
"knockout": "~3.5.0",
"knockout-mapping": "~2.6.0",
"lodash": "~4.17.11",
"numeral": "~2.0.6",
"page": "~1.11.4"
}
}
index.js:
import mochaBaseReporter from 'mocha/lib/reporters/base';
import { takeScreenShot } from './javascript/screenShots';
import { populateTestResults } from './javascript/testTree';
import {
getFileContents,
writeToOutputFile,
} from './javascript/fileSystemAccess';
import {
getTemplate,
parseTestsIntoOutput,
addValuesToTemplate,
} from './javascript/templating';
import {
SUCCESS,
FAILURE,
FINISHED,
} from './constants';
const addStyle = template => getFileContents('styles.css')
.then(styles => addValuesToTemplate(template, { styles }))
.catch(error => console.log('file read of styles.css failed', error));
const createReport = (outputDirectory, fileName, data) => getTemplate('report')
.then(template => addValuesToTemplate(template, { 'test-suites': data }))
.then(template => writeToOutputFile(outputDirectory, `${fileName}.html`, template))
.catch(error => console.log('file read of template.html failed', error));
function mochaReporter(runner, environment) {
const tests = {};
const fileName = 'testfile';
const { outputDir, testDir, takeScreenShotOnFailure } = environment.reporterOptions || {};
const outputDirectory = outputDir && `${process.cwd()}/${outputDir}`;
const accumulateTestResults = (test, image) => populateTestResults(test, testDir, tests, image);
mochaBaseReporter.call(this, runner);
runner.on(SUCCESS, accumulateTestResults);
runner.on(FAILURE, test => (
takeScreenShotOnFailure && window
? takeScreenShot()
: Promise.resolve()
).then(image => accumulateTestResults(test, image)));
runner.on(FINISHED, () => {
parseTestsIntoOutput(tests)
.then(addStyle)
.then(template => addValuesToTemplate(template, runner.stats))
.then(html => createReport(outputDirectory, fileName, html))
.then(() => writeToOutputFile(
`${outputDirectory}/history`,
`test-run-${Date.now()}.json`,
JSON.stringify(tests),
));
});
return runner;
}
module.exports = mochaReporter;
protractor.conf:
/* eslint-disable global-require */
/* eslint-disable #typescript-eslint/no-var-requires */
const protractor = require('protractor');
const { join } = require('path');
const testDirectory = '_src/js/tests';
const baseDirectory = `${testDirectory}/integration/`;
// specifies whether tests will be run in parralel or not
const shardTestFiles = true;
// specifies how many browsers/drivers may be run in parralel
const maxInstances = 4;
function onPrepare() {
// register typescript file extensions with the babel compiler
require('#babel/register')({ extensions: ['.js', '.ts'] });
require('#babel/polyfill');
// don't wait for angular (since our app is currently not angular)
protractor.browser.waitForAngularEnabled(false);
// hot fix for protractor strange map behavior
// found here: https://github.com/angular/protractor/issues/2227#issuecomment-337249891
protractor.ElementArrayFinder.prototype.map = function mapHotFix(mapFn) {
return this.reduce((arr, el) => arr.concat(mapFn(el, arr.length)), []);
};
}
exports.config = {
// mocha configuration
framework: 'mocha',
mochaOpts: {
reporter: './mocha-reporter',
reporterOptions: {
outputDir: `${testDirectory}/reports`,
testDir: `${baseDirectory}/endToEnd`,
takeScreenShotOnFailure: true,
},
timeout: 600000,
slow: 3000,
},
seleniumAddress: 'http://localhost:4444/wd/hub',
// turn off promise management in favor of async/await
SELENIUM_PROMISE_MANAGER: false,
// spec config
specs: [`${baseDirectory}/endToEnd/**/*.spec.js`],
// browser configuration
timeout: 100000,
multiCapabilities: [
{
browserName: 'chrome',
shardTestFiles,
maxInstances,
chromeOptions: {
args: [
// 'show-fps-counter=true',
'--headless',
// '--disable-gpu',
'--window-size=1300,1000',
],
},
},
{
browserName: 'firefox',
shardTestFiles,
maxInstances,
'moz:firefoxOptions': {
args: [
'--headless',
],
},
},
],
onPrepare,
plugins: [
{
package: 'protractor-image-comparison',
options: {
baselineFolder: join(process.cwd(), `${baseDirectory}/screenshots/baseline/`),
screenshotPath: join(process.cwd(), `${baseDirectory}/screenshots/tmp/`),
formatImageName: '{tag}-{logName}-{width}x{height}',
savePerInstance: true,
autoSaveBaseline: true,
},
},
],
};
I could not find a way to load the local file directly, however I gave it a package.json and installed it directly to node_modules with npm. To be specific I ran
npm install ./mocha-reporter --save-dev
on my project directory after creating a package.json within the project folder. After some debugging I was able to solve my issue since the package was now a part of node's named packages.
When I run the test, it thorws "unexpected token error at the code:
const wrapper = shallow(<WelcomeMessage/>");
The error is thrown at "(<". I have looked at a number of answers from stackoverflow and github but somehow I still cannot get it to work.
I have written jest tests. This is my first time writing a test case using enzyme and react. So I am not familar with the setup. I have installed: babel jest, react-dom, babel-plugin-transform-export-extensions, enzyme-adapter-react-16, react-test-renderer, #babel/preset-env, and #babel/core
package.json:
{
"private": true,
"version": "0.0.0",
"name": "example-jquery",
"devDependencies": {
"#babel/core": "*",
"#babel/preset-env": "^7.4.4",
"babel-jest": "^24.8.0",
"babel-plugin-transform-export-extensions": "^6.22.0",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.12.1",
"jest": "^24.8.0",
"jest-dom": "^3.1.4",
"jest-useragent-mock": "0.0.3"
},
"dependencies": {
"jest-puppeteer": "^4.1.1",
"jquery": "^3.4.1",
"jsdom": "^15.0.0",
"puppeteer": "^1.15.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-test-renderer": "^16.8.6"
},
"scripts": {
"test": "jest --verbose"
},
"jest": {
"transform": {
"^.+\\.jsx?$": "babel-jest"
}
}
}
jest.config.js:
module.exports = {
preset: 'jest-puppeteer',
"bail": 0,
setupFiles: ['<rootDir>/enzyme.config.js'],
moduleFileExtensions: ['js', 'json', 'jsx'],
transformIgnorePatterns: ['<rootDir>/node_modules/']
}
enzyme.config.js:
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');
Enzyme.configure({ adapter: new Adapter() });
.babelrc:
{
"presets": ["#babel/preset-env"],
"plugins": ["transform-export-extensions"],
"only": [
"./**/*.js",
"node_modules/jest-runtime"
]
}
WelcomeMessage.test.js:
import React from 'react';
import { shallow } from 'enzyme';
// Components
import WelcomeMessage from './WelcomeMessage';
function setup() {
const props = {
imgPath: 'some/image/path/to/a/mock/image',
};
const wrapper = shallow(<WelcomeMessage />);
return { wrapper, props };
}
describe('WelcomeMessage Test Suite', () => {
it('Should have an image', () => {
const { wrapper } = setup();
expect(wrapper.find('img').exists()).toBe(true);
});
});
This line:
<WelcomeMessage />
is JSX which "just provides syntactic sugar for the React.createElement function".
Since JSX isn't actually valid JavaScript code it must be compiled into React.createElement calls.
This is done by the Babel plugin #babel/plugin-transform-react-jsx which is included as part of #babel/preset-react.
Add #babel/preset-react to your Babel config and that should resolve the issue.