Cannot read property 'runCLI' of undefined in gulp-jest - gulp

I am trying to run jest tests with gulp using gulp-jest.
Installed these packages from npm:
"gulp-jest": "^4.0.3",
"jest-cli": "^25.3.0"
and provided the following configuration to jest:
"jest": {
"setupFilesAfterEnv": [
"<rootDir>/jest.setup.js"
],
"collectCoverage": true,
"coverageDirectory": "./test/unit-test-coverage",
"coverageReporters": [
"text",
"lcov"
]
}
I have written a basic method in my gulpfile.js, referred this link:
function runJsTests() {
process.env.NODE_ENV = 'test';
const __dirname = "Features/Components";
return gulp.src(__dirname).pipe(jest({
}));
}
However, I am getting the following error when I run the gulp task:
TypeError: Cannot read property 'runCLI' of undefined

I had the same trouble last friday, to resolve it, I finally had to downgrade version used of jest-cli :
"#types/jest": "24.9.0",
"jest": "24.9.0",
"ts-jest": "24.3.0
"jest-cli": "24.9.0",
"jest-html-reporter": "2.5.0",
A bug known on new version of Jest-cli
-> think to remove all node_modules and package_lock.json!
Good luck ;)

Related

gulp-eslint Environment key "es2021" is unknown

I have a project with the following dependencies;
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"browser-sync": "^2.26.13",
"del": "^6.0.0",
"eslint": "^7.16.0",
"eslint-config-standard": "^16.0.2",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"gulp": "^4.0.2",
"gulp-cssmin": "^0.2.0",
"gulp-eslint": "^6.0.0",
"gulp-htmllint": "0.0.19",
"gulp-htmlmin": "^5.0.1",
"gulp-imagemin": "^7.1.0",
"gulp-jsmin": "^0.1.5"
When I try to run a gulp task that lints javascript, using eslint/gulp-eslint;
function javascript() {
return src('private/script/**')
//.pipe(jsmin())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError())
.pipe(dest('public/script'));
}
I get the following error;
Error: .eslintrc.json » eslint-config-standard:
Environment key "es2021" is unknown
I used npx eslint --init to generate the following configuration file;
{
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": [
"standard"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 2018
},
"rules": {
}
}
i have done an npm install, to make sure I have the latest version of the dependencies. I have also read on guthub that the error might have something to do with gulp-eslint as it is an old version and might not be using the current version of eslint, however, in I have changed gulp-eslint package.json to use the latest version of eslint and no luck. I also updated node/npm to their latest lts versions.
I fixed this by deleting the eslint folder in the node_modules folder for gulp-eslint. this forces node to use the version you have as a dependency rather than the version the project maintainer wants to use.
it appears this is a known issue.
I solve it by upgrading eslint version to version 7
This is what my package json looks like
The problem is that gulp-eslint works with ESLint 6 under the hub, and ESLint 6 does not support the es2021 environment (see the supported environments of ESLint 6).
I'm going to show three options to handle this. The best solution will depend on your setup and requirements.
Method 1: Replace es2021 with an equivalent definition
The es2021 environment is the same as es2020 with the addition of the globals AggregateError, FinalizationRegistry and WeakRef (see the definition of es2021), so you could enter these settings in your .eslintrc configuration file instead to obtain the same result.
{
...
"env": {
...
"es2020": true
},
...
"globals": {
...
"AggregateError": "readonly",
"FinalizationRegistry": "readonly",
"WeakRef": "readonly"
},
...
}
Method 2: Force gulp-eslint to use ESLint 7
If you are using npm >= 8.3 < 9.0 (check this with npm -v), you can override the version of ESLint used by gulp-eslint.
To do so, first add an override entry to your package.json file like this:
{
...
"overrides": {
"gulp-eslint": {
"eslint": "7"
}
},
...
}
then run:
npm install
Now, gulp-eslint will work with the latest version of ESLint 7 which does recognize the es2021 environment (it exists in ESLint >= 7.8).
Note that gulp-eslint does still not support ESLint 7, so some things may not work as expected. Particularly, some plugins may fail to load or produce runtime errors.
Method 3: Use gulp-eslint-new
gulp-eslint-new works with ESLint 8 and can be used in most situations as a drop-in replacement for gulp-eslint, provided that the configuration is compatible with both versions.
Uninstall gulp-eslint with
npm uninstall gulp-eslint
Install gulp-eslint-new with
npm install -D gulp-eslint-new
In your gulpfile, replace the import of gulp-eslint with gulp-eslint-new.
DISCLAIMER: I am currently the only maintainer of gulp-eslint-new.

"SyntaxError: Unexpected token export" using Jest with babel 7+

I'm trying to cover basic reducer with a test but it throws the error for export in my constants file:
FAIL jest/spec/reducers/RootReducer.spec.js
● Test suite failed to run
Jest encountered an unexpected token
Details:
project-root\js\src\constants\ActionTypes.js:2
export const LOCALE_REQUEST = 'ROOT/LOCALE_REQUEST';
^^^^^^
SyntaxError: Unexpected token export
1 | 'use strict';
2 |
> 3 | import { LOCALE_REQUEST_SUCCESS, ROUTING_REQUEST_SUCCESS } from '/js/src/constants/ActionTypes';
| ^
4 |
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
at Object.<anonymous> (jest/spec/reducers/RootReducer.spec.js:3:1)
I'm running the tests from 'project-root\tests' folder
The js files that I want to test are located in 'project-root\js' folder
I believe this is the reason for the bug. Because the file I'm trying to import is outside of the tests folder it looks like it's not being transpiled
this is my package.json:
{
"name": "jest",
"version": "0.0.0",
"scripts": {
"test": "jest"
},
"devDependencies": {
"#babel/core": "^7.2.2",
"#babel/plugin-transform-modules-commonjs": "^7.2.0",
"#babel/preset-env": "^7.2.3",
"babel-core": "7.0.0-bridge.0",
"jest": "^23.6.0"
}
}
this is .babelrc:
{
"presets": [
"#babel/preset-env"
],
"plugins": [
"#babel/plugin-transform-modules-commonjs"
]
}
this is jest.config.js:
module.exports = {
verbose: true,
transform: {
"^.+\\.jsx?$": "babel-jest"
},
bail: true,
browser: true,
cacheDirectory: '/tmp/jest',
collectCoverage: false,
roots: [
'<rootDir>/../js',
'<rootDir>/jest'
],
moduleNameMapper: {
'^(.*)/js/(.*)$': '<rootDir>/../js/$2'
},
testRegex: '(jest/spec/.*|(\\.|/)(test|spec))\\.js$',
testPathIgnorePatterns: [
'<rootDir>/node_modules'
],
transformIgnorePatterns: [
'/node_modules/'
]
};
So I've tried to look for similar cases around the web but in most cases the problems come from /node_modules or something missing in the jest config. But I can't find what's wrong in my case, would really appreciate any hints what can I try
up: someone suggested that I need to add babel-jest to my package.json but it's already in /node_modules - it is added with jest package
The problem surrounds the fact that you have no babel-loader setup so the project will blow up on import and export commands that do not get removed from the source code during compilation as babel has no idea how to handle that without babel-loader installed and configured.
For a quick example of how to get started with ES6 transpiling and module loading you can check out this example.
youtube.com/watch?v=X5wTsHRsbIA

Can not run protractor with gulp (ECONNREFUSED connect ECONNREFUSED)

I could run it before. But now i cant. It is in a project. My friend who has this project from git latst repository (that is also how i imported) can run protractor under gateway with gulp protractor qa. But for me it gives errors
vegan#vegan:~/xxx-yyyy/gateway$ gulp protractor qa
[16:04:08] Using gulpfile ~/xxx-yyyy/gateway/gulpfile.js
[16:04:08] Starting 'protractor'...
[16:04:08] Starting 'qa'...
[16:04:08] Finished 'qa' after 67 μs
Using ChromeDriver directly...
[launcher] Running 1 instances of WebDriver
/home/vegan/xxx-yyyy/gateway/node_modules/selenium-webdriver/http/index.js:174
callback(new Error(message));
^
Error: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:40886
at ClientRequest.<anonymous> (/home/vegan/xxx-yyyy/gateway/node_modules/selenium-webdriver/http/index.js:174:16)
at emitOne (events.js:90:13)
at ClientRequest.emit (events.js:182:7)
at Socket.socketErrorListener (_http_client.js:306:9)
at emitOne (events.js:90:13)
at Socket.emit (events.js:182:7)
at emitErrorNT (net.js:1265:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
From: Task: WebDriver.createSession()
at Function.webdriver.WebDriver.acquireSession_ (/home/vegan/xxx-yyyy/gateway/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:157:22)
at Function.webdriver.WebDriver.createSession (/home/vegan/xxx-yyyy/gateway/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:131:30)
at new Driver (/home/vegan/xxx-yyyy/gateway/node_modules/selenium-webdriver/chrome.js:810:36)
at [object Object].DirectDriverProvider.getNewDriver (/home/vegan/xxx-yyyy/gateway/node_modules/gulp-protractor/node_modules/protractor/lib/driverProviders/direct.js:68:16)
at [object Object].Runner.createBrowser (/home/vegan/xxx-yyyy/gateway/node_modules/gulp-protractor/node_modules/protractor/lib/runner.js:186:37)
at /home/vegan/xxx-yyyy/gateway/node_modules/gulp-protractor/node_modules/protractor/lib/runner.js:276:21
at _fulfilled (/home/vegan/xxx-yyyy/gateway/node_modules/gulp-protractor/node_modules/q/q.js:797:54)
at self.promiseDispatch.done (/home/vegan/xxx-yyyy/gateway/node_modules/gulp-protractor/node_modules/q/q.js:826:30)
at Promise.promise.promiseDispatch (/home/vegan/xxx-yyyy/gateway/node_modules/gulp-protractor/node_modules/q/q.js:759:13)
at /home/vegan/xxx-yyyy/gateway/node_modules/gulp-protractor/node_modules/q/q.js:525:49
[launcher] Process exited with error code 1
[16:04:10] gulp-notify: [JHipster Gulp Build] Error: protractor exited with code 1
[16:04:10] Finished 'protractor' after 2.41 s
[16:04:10] E2E Tests failed
I did not touch any of conf files of protractor. They are default.
that is in package json
},
"engines": {
"node": "^4.3"
},
this is the error line for 174
request.on('error', function(e) {
if (e.code === 'ECONNRESET') {
setTimeout(function() {
sendRequest(options, callback, opt_data, opt_proxy);
}, 15);
} else {
var message = e.message;
if (e.code) {
message = e.code + ' ' + message;
}
callback(new Error(message));
}
});
this is in packagejson in selenumwebdriver
{
"_args": [
[
"selenium-webdriver#https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-2.48.2.tgz",
"/home/vegan/xxx-yyyy/gateway"
]
],
"_from": "selenium-webdriver#2.48.2",
"_id": "selenium-webdriver#2.48.2",
"_inCache": true,
"_location": "/selenium-webdriver",
"_phantomChildren": {
"bufferutil": "1.2.1",
"options": "0.0.6",
"ultron": "1.0.2",
"utf-8-validate": "1.2.2",
"xmlbuilder": "4.2.1"
},
"_requested": {
"name": "selenium-webdriver",
"raw": "selenium-webdriver#https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-2.48.2.tgz",
"rawSpec": "https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-2.48.2.tgz",
"scope": null,
"spec": "https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-2.48.2.tgz",
"type": "remote"
},
"_requiredBy": [
"/gulp-protractor/protractor",
"/protractor"
],
"_resolved": "https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-2.48.2.tgz",
"_shasum": "b26a4631430d0a9f36284ee0cfe09676e8f348ca",
"_shrinkwrap": null,
"_spec": "selenium-webdriver#https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-2.48.2.tgz",
"_where": "/home/vegan/xx-yyyy/gateway",
"bugs": {
"url": "https://github.com/SeleniumHQ/selenium/issues"
},
"dependencies": {
"adm-zip": "0.4.4",
"rimraf": "^2.2.8",
"tmp": "0.0.24",
"ws": "^0.8.0",
"xml2js": "0.4.4"
},
"description": "The official WebDriver JavaScript bindings from the Selenium project",
"devDependencies": {
"express": "^4.11.2",
"mocha": ">= 1.21.x",
"multer": "^0.1.7",
"promises-aplus-tests": "^2.1.0",
"serve-index": "^1.6.1"
},
"engines": {
"node": ">= 0.12.x"
},
"homepage": "https://github.com/SeleniumHQ/selenium",
"keywords": [
"automation",
"selenium",
"testing",
"webdriver",
"webdriverjs"
],
"license": "Apache-2.0",
"main": "./index",
"name": "selenium-webdriver",
"optionalDependencies": {},
"readme": "# selenium-webdriver\n\nSelenium is a browser automation library. Most often used for testing\nweb-applications, Selenium may be used for any task that requires automating\ninteraction with the browser.\n\n## Installation\n\nSelenium supports Node `0.12.x` and `4.x`. Users on Node `0.12.x` must run with\nthe --harmony flag. Selenium may be installed via npm with\n\n npm install selenium-webdriver\n\nOut of the box, Selenium includes everything you need to work with Firefox. You\nwill need to download additional components to work with the other major\nbrowsers. The drivers for Chrome, IE, PhantomJS, and Opera are all standalone\nexecutables that should be placed on your\n[PATH](http://en.wikipedia.org/wiki/PATH_%28variable%29). The SafariDriver\nbrowser extension should be installed in your browser before using Selenium; we\nrecommend disabling the extension when using the browser without Selenium or\ninstalling the extension in a profile only used for testing.\n\n| Browser | Component |\n| ----------------- | ---------------------------------- |\n| Chrome | [chromedriver(.exe)][chrome] |\n| Internet Explorer | [IEDriverServer.exe][release] |\n| PhantomJS | [phantomjs(.exe)][phantomjs] |\n| Opera | [operadriver(.exe)][opera] |\n| Safari | [SafariDriver.safariextz][release] |\n\n## Usage\n\nThe sample below and others are included in the `example` directory. You may\nalso find the tests for selenium-webdriver informative.\n\n var webdriver = require('selenium-webdriver'),\n By = require('selenium-webdriver').By,\n until = require('selenium-webdriver').until;\n\n var driver = new webdriver.Builder()\n .forBrowser('firefox')\n .build();\n\n driver.get('http://www.google.com/ncr');\n driver.findElement(By.name('q')).sendKeys('webdriver');\n driver.findElement(By.name('btnG')).click();\n driver.wait(until.titleIs('webdriver - Google Search'), 1000);\n driver.quit();\n\n### Using the Builder API\n\nThe `Builder` class is your one-stop shop for configuring new WebDriver\ninstances. Rather than clutter your code with branches for the various browsers,\nthe builder lets you set all options in one flow. When you call\n`Builder#build()`, all options irrelevant to the selected browser are dropped:\n\n var webdriver = require('selenium-webdriver'),\n chrome = require('selenium-webdriver/chrome'),\n firefox = require('selenium-webdriver/firefox');\n\n var driver = new webdriver.Builder()\n .forBrowser('firefox')\n .setChromeOptions(/* ... */)\n .setFirefoxOptions(/* ... */)\n .build();\n\nWhy would you want to configure options irrelevant to the target browser? The\n`Builder`'s API defines your _default_ configuration. You can change the target\nbrowser at runtime through the `SELENIUM_BROWSER` environment variable. For\nexample, the `example/google_search.js` script is configured to run against\nFirefox. You can run the example against other browsers just by changing the\nruntime environment\n\n # cd node_modules/selenium-webdriver\n node example/google_search\n SELENIUM_BROWSER=chrome node example/google_search\n SELENIUM_BROWSER=safari node example/google_search\n\n### The Standalone Selenium Server\n\nThe standalone Selenium Server acts as a proxy between your script and the\nbrowser-specific drivers. The server may be used when running locally, but it's\nnot recommend as it introduces an extra hop for each request and will slow\nthings down. The server is required, however, to use a browser on a remote host\n(most browser drivers, like the IEDriverServer, do not accept remote\nconnections).\n\nTo use the Selenium Server, you will need to install the\n[JDK](http://www.oracle.com/technetwork/java/javase/downloads/index.html) and\ndownload the latest server from [Selenium][release]. Once downloaded, run the\nserver with\n\n java -jar selenium-server-standalone-2.45.0.jar\n\nYou may configure your tests to run against a remote server through the Builder\nAPI:\n\n var driver = new webdriver.Builder()\n .forBrowser('firefox')\n .usingServer('http://localhost:4444/wd/hub')\n .build();\n\nOr change the Builder's configuration at runtime with the `SELENIUM_REMOTE_URL`\nenvironment variable:\n\n SELENIUM_REMOTE_URL=\"http://localhost:4444/wd/hub\" node script.js\n\nYou can experiment with these options using the `example/google_search.js`\nscript provided with `selenium-webdriver`.\n\n## Documentation\n\nAPI documentation is included in the `docs` directory and is also available\nonline from the [Selenium project][api]. Addition resources include\n\n- the #selenium channel on freenode IRC\n- the [selenium-users#googlegroups.com][users] list\n- [SeleniumHQ](http://www.seleniumhq.org/docs/) documentation\n\n## Contributing\n\nContributions are accepted either through [GitHub][gh] pull requests or patches\nvia the [Selenium issue tracker][issues]. You must sign our\n[Contributor License Agreement][cla] before your changes will be accepted.\n\n## Issues\n\nPlease report any issues using the [Selenium issue tracker][issues]. When using\nthe issue tracker\n\n- __Do__ include a detailed description of the problem.\n- __Do__ include a link to a [gist](http://gist.github.com/) with any\n interesting stack traces/logs (you may also attach these directly to the bug\n report).\n- __Do__ include a [reduced test case][reduction]. Reporting \"unable to find\n element on the page\" is _not_ a valid report - there's nothing for us to\n look into. Expect your bug report to be closed if you do not provide enough\n information for us to investigate.\n- __Do not__ use the issue tracker to submit basic help requests. All help\n inquiries should be directed to the [user forum][users] or #selenium IRC\n channel.\n- __Do not__ post empty \"I see this too\" or \"Any updates?\" comments. These\n provide no additional information and clutter the log.\n- __Do not__ report regressions on closed bugs as they are not actively\n monitored for upates (especially bugs that are >6 months old). Please open a\n new issue and reference the original bug in your report.\n\n## License\n\nLicensed to the Software Freedom Conservancy (SFC) under one\nor more contributor license agreements. See the NOTICE file\ndistributed with this work for additional information\nregarding copyright ownership. The SFC licenses this file\nto you under the Apache License, Version 2.0 (the\n\"License\"); you may not use this file except in compliance\nwith the License. You may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, either express or implied. See the License for the\nspecific language governing permissions and limitations\nunder the License.\n\n[api]: http://seleniumhq.github.io/selenium/docs/api/javascript/\n[cla]: http :/ /go o.gl/qC50R\n[chrome]: http://chromedriver.storage.googleapis.com/index.html\n[gh]: https://github.com/SeleniumHQ/selenium/\n[issues]: https://github.com/SeleniumHQ/selenium/issues\n[opera]: https://github.com/operasoftware/operachromiumdriver/releases\n[phantomjs]: http://phantomjs.org/\n[reduction]: http://www.webkit.org/quality/reduction.html\n[release]: http://selenium-release.storage.googleapis.com/index.html\n[users]: https://groups.google.com/forum/#!forum/selenium-users\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/SeleniumHQ/selenium.git"
},
"scripts": {
"test": "mocha --harmony -t 600000 --recursive test"
},
"version": "2.48.2"
}
those are versions
vegan#vegan:~/xx-yyyy/gateway$ node -v
v5.12.0
vegan#vegan:~/xx-yyyy/gateway$ npm -v
3.8.6
my friend also has this versions but he can run Also i could until lasst week. I dont know what happened. I deleted node modules, resetted all but did not work.
i dont know what i can give information about.
i also tried this
https://stackoverflow.com/a/34758398/6804200
changed configjson to this
{
"webdriverVersions": {
"seleniumServerJar": './node_modules/protractor/selenium/selenium-server-standalone-2.51.0.jar',
"chromedriver": "2.21",
"iedriver": "2.51.0"
}
}
but nothng changed.
i did also npm update
gulp protractor is
gulp.task(
'protractor', function () {
configObj['args'] = [];//to be able to add multiple parameters
if (argv.suite) {
configObj['args'].push(
'--suite',
argv.suite
);
}
return gulp.src([])
.pipe(plumber({errorHandler: handleErrors}))
.pipe(protractor(configObj))
.on(
'error', function () {
gutil.log('E2E Tests failed');
process.exit(1);
}
);
}
);
var configObj = {
configFile: config.test + 'protractor.conf.js'
};
protractorconf is
var HtmlScreenshotReporter = require("protractor-jasmine2-screenshot-reporter");
var JasmineReporters = require('jasmine-reporters');
var prefix = 'src/test/javascript/'.replace(/[^/]+/g, '..');
exports.config = {
chromeDriver: prefix + 'node_modules/protractor/selenium/chromedriver',
allScriptsTimeout: 240000,
suites: {
register: './e2e/account/register/*.js',
login: './e2e/account/login/*.js'
},
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
framework: 'jasmine2',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 240000
},
onPrepare: function () {
var disableNgAnimate = function () {
angular
.module('disableNgAnimate', [])
.run(
[
'$animate',
function ($animate) {
$animate.enabled(false);
}
]
);
};
var disableCssAnimate = function () {
angular
.module('disableCssAnimate', [])
.run(
function () {
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = 'body * {' +
'-webkit-transition: none !important;' +
'-moz-transition: none !important;' +
'-o-transition: none !important;' +
'-ms-transition: none !important;' +
'transition: none !important;' +
'}';
document.getElementsByTagName('head')[0].appendChild(style);
}
);
};
browser.addMockModule('disableNgAnimate', disableNgAnimate);
browser.addMockModule('disableCssAnimate', disableCssAnimate);
browser.driver.manage().window().maximize();
}
};
gulp tasks of qa
gulp.task('qa', function () {
argv.baseUrl = qaurl;
configObj['args'].push(
'--baseUrl',
argv.baseUrl
);
});
i got this when i do npm install
npm WARN lifecycle gateway#0.0.0~postinstall: cannot run in wd %s %s
(wd=%s) gateway#0.0.0 webdriver-manager update
/home/vegan/xx-yyy/gateway npm WARN optional Skipping failed optional
dependency /chokidar/fsevents: npm WARN notsup Not compatible with
your operating system or architecture: fsevents#1.0.17
also i get this
vegan#vegan:~/xx-yyy/gateway$ sudo npm install -g protractor
npm WARN deprecated minimatch#0.3.0: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
/usr/bin/protractor -> /usr/lib/node_modules/protractor/bin/protractor
/usr/bin/webdriver-manager -> /usr/lib/node_modules/protractor/bin/webdriver-manager
/usr/lib
└─┬ protractor#5.0.0
└── source-map-support#0.4.11
it is a spring boot project. it uses gulp. the project is not needed to be up to run the protractor.
Remove & reinstall npm, gulp, nodejs.
Could you please update the gulp-protractor-qa plugin. Mean while i hope you are using gulp-protractor update that also.
Update gulp-protractor to version 3.0.0
npm update gulp-protractor & give a try it should work.

Does Jest support ES6 import/export?

If I use import/export from ES6 then all my Jest tests fail with error:
Unexpected reserved word
I convert my object under test to use old school IIFE syntax and suddenly my tests pass. Or, take an even simpler test case:
var Validation = require('../src/components/validation/validation'); // PASS
//import * as Validation from '../src/components/validation/validation' // FAIL
Same error. Obviously there's a problem with import/export here. It's not practical for me to rewrite my code using ES5 syntax just to make my test framework happy.
I have babel-jest. I tried various suggestions from GitHub issues. It is no go so far.
File package.json
"scripts": {
"start": "webpack-dev-server",
"test": "jest"
},
"jest": {
"testPathDirs": [
"__tests__"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testFileExtensions": ["es6", "js"],
"moduleFileExtensions": ["js", "json", "es6"]
},
File babelrc
{
"presets": ["es2015", "react"],
"plugins": ["transform-decorators-legacy"]
}
Is there a fix for this?
From my answer to another question, this can be simpler:
The only requirement is to configure your test environment to Babel, and add the ECMAScript 6 transform plugin:
Step 1:
Add your test environment to .babelrc in the root of your project:
{
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Step 2:
Install the ECMAScript 6 transform plugin:
npm install --save-dev #babel/plugin-transform-modules-commonjs
And that's it. Jest will enable compilation from ECMAScript modules to CommonJS automatically, without having to inform additional options to your jest property inside package.json.
UPDATE 2020 - native support of ECMAScript modules (ESM)
According to this issue, there is native support of ESM from jest#25.4.0. So you won't have to use babel anymore. At the time of writing this answer (05/2020), to activate that you need to do three simple things:
Make sure you don't transform away import statements by setting transform: {} in config file
Run node#^12.16.0 || >=13.2.0 with --experimental-vm-modules flag
Run your test with jest-environment-node or jest-environment-jsdom-sixteen.
So your Jest configuration file should contain at least this:
export default {
testEnvironment: 'jest-environment-node',
transform: {}
...
};
And to set --experimental-vm-modules flag, you will have to run Jest as follows:
node --experimental-vm-modules node_modules/jest/bin/jest.js
Also note in the Github issue that this approach does not yet support the jest object. So you may need to import it manually:
import {jest} from '#jest/globals'
(I hope this will change in the future)
For an updated configuration, I'm using https://babeljs.io/setup#installation
Select JEST and be happy:
As a reference, the current configuration:
npm install --save-dev babel-jest
In your package.json file, make the following changes:
{
"scripts": {
"test": "jest"
},
"jest": {
"transform": {
"^.+\\.jsx?$": "babel-jest"
}
}
}
Install babel preset:
npm install #babel/preset-env --save-dev
Create a .babelrc file:
{
"presets": ["#babel/preset-env"]
}
Run your tests:
npm run test
In package.json, kindly set like this one: "test": "node --experimental-vm-modules node_modules/.bin/jest"
Should be good!
It's a matter of adding stage-0 to your .babelrc file. Here is an example:
{
"presets": ["es2015", "react", "stage-0"],
"plugins": ["transform-decorators-legacy"]
}
I encountered the same issue.
These are what I did:
yarn add --dev babel-jest #babel/core #babel/preset-env
Make file jest.config.js in rootDir.
module.exports = {
moduleFileExtensions: ["js", "json", "jsx", "ts", "tsx", "json"],
transform: {
'^.+\\.(js|jsx)?$': 'babel-jest'
},
testEnvironment: 'node',
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/$1'
},
testMatch: [
'<rootDir>/**/*.test.(js|jsx|ts|tsx)', '<rootDir>/(tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx))'
],
transformIgnorePatterns: ['<rootDir>/node_modules/']
};
Then make file babal.config.js in rootDir.
Go like this:
module.exports = {
"presets": ["#babel/preset-env"]
}
Below is how I setup jest, typescript and ES Modules for my project.
jest.config.js
/**
* #type {import('ts-jest/dist/types').InitialOptionsTsJest}
* To configure ESM support, see: https://kulshekhar.github.io/ts-jest/docs/guides/esm-support
*
**/
export default {
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'node',
extensionsToTreatAsEsm: ['.ts'],
globals: {
'ts-jest': {
useESM: true
}
},
setupFiles: ['<rootDir>/__tests__/setup.ts'],
};
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"outDir": "./dist",
"moduleResolution": "node",
// "strict": true,
"esModuleInterop": true,
"inlineSourceMap": true,
}
}
package.json scripts and devDependencies
"scripts": {
"start": "node ./dist/server.js",
"dev": "tsc-watch --onSuccess \"node ./dist/server.js\"",
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
},
"devDependencies": {
"#jest/globals": "^27.4.4",
"#types/express": "^4.17.13",
"#types/jest": "^27.4.0",
"#types/supertest": "^2.0.11",
"cross-env": "^7.0.3",
"supertest": "^6.2.1",
"ts-jest": "^27.1.3"
}
__tests__/setup.ts
import dotenv from 'dotenv';
dotenv.config({
path: './.env.test'
});
all is explained in the jest docs: jest docs
1.
npm install --save-dev babel-jest #babel/core #babel/preset-env
in file: babel.config.js
module.exports = {
presets: [['#babel/preset-env', {targets: {node: 'current'}}]],
};
In addition to installing babel-jest (which comes with Jest by default now) be sure to install regenerator-runtime.
To add support for React and react-testing-library it may be useful to eject CreateReactApp and take all needed Jest configuration from the package.json. It is ready to use with another bundler, Rollup in my case.

gulp-jshint: How to fail the build?

I want my Gulp build to fail, if there are errors in JSHint.
According to the documentation of gulp-jshint I can use the "fail reporter".
However the following does not work:
gulp.task("lint", function() {
return gulp.src(JS_SOURCES)
.pipe(jshint())
.pipe(jshint.reporter("jshint-stylish"))
.pipe(jshint.reporter("fail"));
});
The task above always returns with exit code 0, even when there are errors in JSHint.
I am using gulp 3.8.10 and gulp-jshint 1.9.0.
There are discussions in the github issues of gulp-jshint here and here ... but according those discussions I gather that above code should work with the latest versions of gulp and gulp-jshint. However it does not ...
Has anybody figured out how to fail the build properly with gulp-jshint?
TLDR;
Until GulpJS comes with a good solution in a stable release, use the workaround as suggested by Bahmutov on GitHub.
He creates a workaround, using his own filter:
var map = require('map-stream');
var exitOnJshintError = map(function (file, cb) {
if (!file.jshint.success) {
console.error('jshint failed');
process.exit(1);
}
});
gulp.task('lint', function() {
gulp.src('example.js')
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(exitOnJshintError);
});
Long answer
This question has been posted as an issue on GitHub: How to fail gulp build? #6 . Pay special attention to Bahmutov's comment.
The solution (hack) he proposes is to add his own filter and do a process.exit(1); when there are hinting errors, which looks like this:
var map = require('map-stream');
var exitOnJshintError = map(function (file, cb) {
if (!file.jshint.success) {
console.error('jshint failed');
process.exit(1);
}
});
gulp.task('lint', function() {
gulp.src('example.js')
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(exitOnJshintError);
});
This issue links to another issue Plugin doesn't fail build #10.
What they say here basically, is that Gulp should take care of the build failing.
This results in another issue which has been reported on GulpJS: Controlling failing builds #113. Which on his turn has been move to "finish then fail" #20.
The latter one has been fixed and the Gulp JS release can be tracked on: changing this #347.
So, we'll have to wait for it to be released...
In the mean time, we can use the workaround as mentioned at the top of my post in the TLDR;
I've implemented it my gulpfile.js in task scripts-app.
It works for me. I have the same gulp task:
return gulp.src(['./src/**/*.js', './docs_src/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jshint.reporter('fail'))
and here's what happens:
$ gulp --version
[11:03:41] CLI version 3.9.0
[11:03:41] Local version 3.9.0
[14559:3392 - 0:2151] 11:03:41 [tony#tony-lin:o +1] ~/work/solo/fsstatic2 (master)
$ cat package.json
{
"name": "fsstatic2",
"version": "0.0.0",
"description": "fsstatic",
"author": "FreedomSponsors",
"devDependencies": {
"gulp": "~3.9.0",
"gulp-concat": "~2.5.2",
"gulp-linker": "~0.1.7",
"gulp-webserver": "~0.9.1",
"yargs": "~3.12.0",
"gulp-sass": "~2.0.1",
"gulp-ng-templates": "0.0.6",
"gulp-ngtemplate": "~0.2.5",
"gulp-htmlmin": "~1.1.3",
"merge-stream": "~0.1.7",
"gulp-copy": "0.0.2",
"gulp-jshint": "~1.11.0",
"jshint-stylish": "~2.0.1"
}
}
[14559:3392 - 0:2152] 11:04:01 [tony#tony-lin:o +1] ~/work/solo/fsstatic2 (master)
$ gulp jshintall
[11:04:11] Using gulpfile ~/work/solo/fsstatic2/gulpfile.js
[11:04:11] Starting 'jshintall'...
/home/tony/work/solo/fsstatic2/src/components/todo_example/todo.js
line 26 col 23 Missing semicolon.
⚠ 1 warning
[11:04:11] 'jshintall' errored after 467 ms
[11:04:11] Error in plugin 'gulp-jshint'
Message:
JSHint failed for: /home/tony/work/solo/fsstatic2/src/components/todo_example/todo.js
[14559:3392 - 0:2153] 11:04:11 [tony#tony-lin:o +1] ~/work/solo/fsstatic2 (master)
$ echo $?
1