In Vuejs project,
node version: v10.6.0
Package.json version:
"devDependencies": {
"#vue/cli-plugin-babel": "^3.0.0-rc.4",
"#vue/cli-plugin-unit-jest": "^3.0.0-rc.4",
"#vue/cli-service": "^3.0.0-rc.4",
"#vue/test-utils": "^1.0.0-beta.20",
"babel-core": "7.0.0-bridge.0",
"babel-jest": "^23.0.1",
"vue-template-compiler": "^2.5.16"
},
When I run it with build in tasks,
"test:unit": "vue-cli-service test:unit"
But as I want to debug, so I run manually with node command:
node node_modules/.bin/jest
It gives following error:
FAIL tests/unit/HelloWorld1.spec.js
● Test suite failed to run
.../tests/unit/HelloWorld1.spec.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import "core-js/modules/es6.array.iterator";
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected string
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
After I added .babelrc with following content
{"env": {
"development": {
"plugins": ["transform-es2015-modules-commonjs"]
},
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}}
Things got a little better, It can pass the the test file without "import", once there's import, it will show a different error:
....tests/unit/HelloWorld1.spec.js:3
import _interopRequireWildcard from "..../node_modules/#babel/runtime/helpers/builtin/es6/interopRequireWildcard";
^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
After struggling for a few days. Finally, I got the solution to run jest in debug mode for VueJs application.
After debuging into vue-cli-service and in turn #vue/cli-plugin-unit-jest, I found the following code before it spawns the jest process:
process.env.VUE_CLI_BABEL_TARGET_NODE = true
process.env.VUE_CLI_BABEL_TRANSPILE_MODULES = true
Solution
So the solution is very simple.
Just add these two environment variables before running the jest command. The following commands will start jest in debug mode:
export VUE_CLI_BABEL_TARGET_NODE=true
export VUE_CLI_BABEL_TRANSPILE_MODULES=true
./node_modules/jest/bin/jest.js --clearCache
node --inspect-brk ./node_modules/jest/bin/jest.js -i
Notes
Make sure DON'T add ".babel.rc", this will mass up VueJS babel.
And often, you will need to run jest with the --clearCache option. Otherwise, the stale generated file will also mess up.
The jest option -i is also important. Otherwise, the test will be running in a separate process which will not be in debug mode.
Had the same issue.
FAIL tests/unit/example.spec.js
● Test suite failed to run
.../tests/unit/example.spec.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import "core-js/modules/es6.array.find";
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected string
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
Tried the answer above.This article solved my problem.
Solution:
npm uninstall "#vue/cli-plugin-unit-jest"
deleted tests folder with all content
deleted jest.config.js file
vue add #vue/cli-plugin-unit-jest
for VS Code use the next launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "vscode-jest-tests",
"type": "node",
"request": "launch",
"runtimeArgs": [
"--inspect-brk",
"./node_modules/#vue/cli-service/bin/vue-cli-service.js",
"test:unit",
"--runInBand"
],
"cwd": "${workspaceFolder}",
"protocol": "inspector",
"disableOptimisticBPs": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"outFiles": [ "${workspaceFolder}/src/**/*.js"],
"port": 9229
},
]
}
Another solution is to ensure your Node Environment is resolving correctly.
In my case, it would resolve to "development". Updating my package.json to the following resolved the issue:
"test": "NODE_ENV=test jest"
This will ensure that your babel config uses the test configuration.
Was your test suite working before and now it's throwing this error? This is what happened to me and before going off the deep-end there is a decent chance that something is cached that is causing this.
I resolved it using: npm test -- -u
If that fails you should delete your node_modules folder and do a fresh npm install and then try npm cache clean --force.
Another useful command if you want to run the tests without cache is npm test -- --no-cache -u.
Related
For instance, I want to run jest tests for one of my packages.
I set up the test script in the child package.json:
"test" : "jest"
However when I got to the package directory and run:
npm test
I get:
sh: jest: command not found
This makes sense because I've only installed jest in the root package since it is a dev dependency.
What do I need to do to make the npm package jest available in the child packages?
We're using an npm package called env-cmd https://www.npmjs.com/package/env-cmd to run scripts from root level in packages.
our root package.json looks something like this:
{
"name": "#myAwesomeApp/root",
"private": true,
"devDependencies": {
"env-cmd": "^10.1.0",
"lerna": "^5.0.0"
},
"dependencies": {
[...]
},
"workspaces": [
"packages/*"
],
"scripts": {
"internal:warning": "echo \"\n\t\\\\033[32m! ANY NOTIFICATION !\n\"",
"jest": "npm run internal:warning && env-cmd --silent lerna run test"
}
}
For a library written in ES6/7, I want to compile (to ES5) the library to a dist/ folder. I also want to run the tests (written in ES6/7) for this lib.
My dev dependencies look like this (package.json):
"devDependencies": {
"#babel/cli": "^7.4.4",
"#babel/core": "^7.4.5",
"#babel/preset-env": "^7.4.5",
"#babel/register": "^7.4.4",
"chai": "^4.2.0",
"mocha": "^6.1.4",
"sinon": "^7.3.2"
},
My build and test scripts looks like this (package.json):
"scripts": {
"test": "mocha --require #babel/register",
"build": "babel src -d dist --presets=#babel/preset-env"
},
Running npm run build works well. The dist/ folder gets populated with transpiled files.
Running npm run test does not seem to work - this is my problem.
> mocha --require #babel/register
/Users/dro/Repos/lib/node_modules/yargs/yargs.js:1163
else throw err
^
ReferenceError: regeneratorRuntime is not defined
Initially I got an import error, which was resolved by adding .babelrc file.
Below is my .babelrc file content.
{
"presets": ["#babel/preset-env"]
}
I was reading about regeneratorRuntime and it got me to this link about babel-polyfill where they explain I shouldn't need that polyfill.
This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool.
What is needed to set this up properly?
I am not using webpack.
Testing in ES6 with Mocha and Babel 7. Look here: https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei or http://jamesknelson.com/testing-in-es6-with-mocha-and-babel-6/
npm install --save #babel/runtime
npm install --save-dev #babel/plugin-transform-runtime
And, in .babelrc, add:
{
"presets": ["#babel/preset-env"],
"plugins": [
["#babel/transform-runtime"]
]
}
Look at the project documentation:
npm install --save-dev babel-register
In your package.json file make the following changes:
{
"scripts": {
"test": "mocha --require babel-register"
}
}
Some features will require a polyfill:
npm install --save-dev babel-polyfill
{
"scripts": {
"test": "mocha --require babel-polyfill --require babel-register"
}
}
Below steps are for applying Babel transformations & core-js polyfills for your tests file:
💡 All transformations are only done per current environment, so only what is needed to be transpiled/polyfilled, will be. Target environments may be defined from a .browserslist file or as a property in package.json file. (read more here)
Step 1: Install packages:
#babel/core (read why)
#babel/preset-env (read why)
#babel/register (read why)
core-js (read why)
Note that #babel/polyfill exists and uses core-js under the hood. However, it was deprecated in favor of using core-js directly.
Step 2: Create a Babel configuration file babel.config.js
(used to be .babelrc.js or a .json file).
Create this file at the root-level of your code.
The most basic configuration (for just testing and not bundling) would look like this:
module.exports = {
presets: [
['#babel/preset-env', {
"corejs": "3.26",
"useBuiltIns": "usage"
}],
};
corejs - This is the polyfills library and should be specified with the minor version, otherwise x.0 will be used.
It is needed when testing code on rather "old" Node versions, which do not support all of the language methods. This ofc depends on your own usage of such javascript methods. (for example String.prototype.replaceAll).
useBuiltIns - must be set in order for the corejs polyfills to be applied. Read about it in the official docs.
By default, #babel/preset-env will compile your code for the current environment, but you can specify a different environment by setting the "targets" option in the configuration.
Ofc, you can add more presets like #babel/preset-react for example, if your code it written in React, or any other plugins which are specifically needed for your code.
Step 3: Connect mocha to the babel configuration:
In your package.json file
Under the scripts section, simply write something like this:
"test": "mocha \"src/**/*.test.js\""
Create a .mocharc.json file with this content:
{
"exit": true,
"color": true,
"require": ["#babel/register"],
"ignore": "node_modules"
}
This will apply Babel transformations to all of your test files.
If you need need to apply some special global javascript before/to all of your tests, you can add another file to the require setting, for example, fixtures.cjs:
"require": ["#babel/register", "fixtures.cjs"],
fixtures.cjs:
Below example applies a chai (popular alongside Mocha) plugin for testing DOM-related code:
var chai = require('chai'),
chaiDOM = require('chai-dom');
// https://stackoverflow.com/questions/62255953/chai-usechaihttp-once-or-in-every-test-file
// https://mochajs.org/#global-teardown-fixtures
exports.mochaGlobalSetup = function () {
chai.use(chaiDOM);
}
Interesting reads:
Babel vs babel-core vs babel-runtime
How does mocha / babel transpile my test code on the fly?
I was able to run "npm start" before ejecting CRA.
After I performed "npm run eject" build is getting failed due to lint errors and unable to run localhost.
If linting errors are reasons behind build failed, why app was working before ejecting?
You can disable that by adding emitWarning: true to the options of eslint-loader.
{
test: /\.(js|jsx|mjs)$/,
enforce: "pre",
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve("eslint"),
emitWarning: true,
},
loader: require.resolve("eslint-loader"),
},
],
include: paths.appSrc,
}
In my case, I have configured Eslint and Airbnb with following versions.
"eslint": "^5.5.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jsx-a11y": "^6.1.1",
"eslint-plugin-react": "^7.11.1"
After ejecting I found that in package.json there are two different versions of eslint.
So I think due to version mismatch of eslint that Airbnb and CreateReactApp require app building is getting failed.
Some reference
I'm using the following package.json (according to http://facebook.github.io/jest/docs/tutorial-react-native.html#content):
{
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest",
},
"dependencies": {
"react": "^15.3.1",
"react-native": "0.31.0",
},
"devDependencies": {
"babel-jest": "^14.1.0",
"babel-preset-react-native": "^1.9.0",
"jest": "^14.1.0",
"jest-cli": "^13.1.0",
"jest-react-native": "^14.1.3",
"react-test-renderer": "^15.3.1"
},
"jest": {
"globals": {
"__DEV__": true,
"__RCTProfileIsProfiling": false
},
"preset": "jest-react-native"
}
}
But I get the error:
Error: Unknown config option "preset" with value "jest-react-native". This is either a typing error or another user mistake and fixing it will remove this message.
Using Jest CLI v13.2.3, jasmine2, babel-jest
FAIL __tests__/AuthorRequest-test.js (0s)
● Runtime Error
- Error: Cannot find module 'throwOnWrongReactAPI' from 'react-native.js'
at Resolver.resolveModule (node_modules/jest-cli/node_modules/jest-resolve/build/index.js:197:17)
at eval (node_modules/react-native/Libraries/react-native/react-native.js:180:26)
at Object.<anonymous> (node_modules/react-native/Libraries/react-native/react-native.js:189:4)
1 test suite failed, 0 tests passed (0 total in 1 test suite, run time 2.238s)
npm ERR! Test failed. See above for more details.
my .babelrc file contains:
{
"presets": ["react-native"]
}
I have a feeling that you are using a wrong version of Jest. You have:
"jest": "^14.1.0",
"jest-cli": "^13.1.0"
But it seems you have 13.2.3installed using npm -g:
Using Jest CLI v13.2.3, jasmine2, babel-jest
First of all, I think you can remove jest-cli and just use jest 14.1.0.
Then you can update your test script like:
"scripts": {
"test": "./node_modules/jest/bin/jest.js"
}
In this way, you make sure you run the local Jest copy of your project, so it should say now:
Using Jest CLI v14.1.0, jasmine2, babel-jest
Doing that and following the official docs you posted, it should be everything you need (Can't say for sure since you did not post the test code).
When I change my files while webpack-dev-server is running, the bundle's files are not updated.
Here are my webpack.config.js and package.json files, as you can see from my npm script, I've solved running webpack watch and webpack-dev-server in the same command (npm run watch & webpack-dev-server --content-base ./ --port 9966):
webpack.config.js:
'use strict';
var ReactStylePlugin = require('react-style-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack');
module.exports = {
devtool: 'sourcemap',
entry: ['./js/main.js'],
output: {
filename: 'bundle.js',
path: __dirname + '/assets',
publicPath: __dirname + '/'
},
module: {
loaders: [
{
test: /\.js$/,
loaders: [
ReactStylePlugin.loader(),
'jsx-loader?harmony'
]
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('css-loader')
}
]
},
plugins: [
new ReactStylePlugin('bundle.css'),
new webpack.DefinePlugin({
'process.env': {
// To enable production mode:
//NODE_ENV: JSON.stringify('production')
}
})
]
}
package.json:
{
"name": "reactTest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"build": "webpack",
"web": "npm run watch & webpack-dev-server --content-base ./ --port 9966"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^0.10.1",
"extract-text-webpack-plugin": "^0.3.8",
"jsx-loader": "^0.13.1",
"react-style-webpack-plugin": "^0.4.0",
"style-loader": "^0.10.2",
"url-loader": "^0.5.5",
"webpack": "^1.8.5",
"webpack-dev-server": "^1.8.0"
},
"dependencies": {
"react": "^0.13.1",
"react-style": "^0.5.3"
}
}
my directory structure is:
assets
bundle.css
bundle.css.map
bundle.js
bundle.js.map
js
AppActions.js
Profile.css.js
ProfileList.js
main.js
AppConstants.js
AppStore.js
Profile.js
ResultPage.js
package.json
index.html
node_modules
webpack.config.js
every file inside assets directory is generated by webpack
In order to get webpack to watch my file changes (Ubuntu 14.04), I had to increase the number of watchers (I had increased the number before, but it was still too low):
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
Source in the official docs: https://webpack.github.io/docs/troubleshooting.html#not-enough-watchers
I first suspected the cause to be fsevents which doesn't work on Ubuntu, but this apparently wasn't the case.
Furthermore, because now the watching and re-compiling worked, but the automatic browser refresh part didn't work, I added the --inline param to the answer of #deowk which enables the "inline mode":
webpack-dev-server --content-base ./ --port 9966 --hot --inline
Quote from the official docs: "The easiest way to use Hot Module Replacement with the webpack-dev-server is to use the inline mode."
Source: https://webpack.github.io/docs/webpack-dev-server.html#hot-module-replacement
you need to run webpack-dev-server with the --hot flag:
webpack-dev-server --content-base ./ --port 9966 --hot
Then you can access the hot-loading version localhost:9966/webpack-dev-server/
You don't need to run watch as well.
update:
This entry in your webpack config must change:
entry: ['./js/main.js'], --> entry: ['webpack/hot/dev-server' , './js/main.js']
Change your publicPath entry:
publicPath: '/assets/'
#funkybunky identified the right problem but (IMHO) fixed it the wrong way. At least in my case, webpack was trying to watch every file it used, including a deep chain of thousands of files of dependencies pulled from npm. I added this to my config, per the docs:
devServer: {
watchOptions: {
ignored: /node_modules/
}
}
Of course you legitimately could have thousands of files that might need to be watched, in which case go ahead and raise the limit, but you're probably better off ignoring vendor libraries that aren't likely to change.
I'll put this here just in case it helps anyone. My problem was the same, but caused by inconsistent capitalization of directory names and webpack alias declaration.
I had a WebGL directory which i referenced in my aliases as webgl, and unfortunately this worked for the build, but didn't work for code watching.
In my case, the error was caused by an empty space in the directory name, by changing "Repository Name" by "RepositoryName", everything worked fine !
Figured I'd post my solution as well. I had the same problem getting Flutter apps to run on OS X due to my hard drive setup.
The gist is if your project folder is in a symlinked folder, detecting the file changes may not work on OS X. Previously, we were on Webpack 3.X, I believe, and live reload/refresh worked fine in the original folder. However, after upgrading to the latest Webpack (^5.75.0) and Webpack Dev Server (^4.11.1), the hot-reloading no longer worked for me.
My original project folder was:
/Users/blakemiller/h/somefolder/v2/my-widget
The "/h" there is a symlink to: /System/Volumes/Data/projects/home/web/
I'm not sure what happened when I upgraded OS X at some point, but the upgrade changed the folders in a way that I don't really understand.
Putting the folder here instead, fixed the issue for me (no symlink):
/Users/blakemiller/my-widget
I doubt this will work for many people, as my setup is probably pretty specific, but maybe it will help someone else save 5 hours down the road...