Configure jest with latest version of d3-path - javascript

For some reason, my jest configuration doesn't work with the latest version of d3-path#3.0.1. It worked fine with version 2.0.0. I guess it has something to do with d3-path switching to ESM, but I was already using ES6 in my own code, so I don't get why it suddenly doesn't work anymore. I have the following packages installed:
"dependencies": {
"d3-path": "^3.0.1"
},
"devDependencies": {
"#babel/core": "^7.15.8",
"#babel/preset-env": "^7.15.8",
"babel-jest": "^27.3.1",
"jest": "^27.3.1"
}
My babel.config.js:
module.exports = {
presets: [['#babel/preset-env', {targets: {node: 'current'}}]],
};
My index.js:
import { path } from 'd3-path'
export default () => path()
The test file:
import fn from '../src/index.js'
describe('test', () => {
it('works', () => {
fn()
expect(2 + 2).toBe(4)
})
})
The error message:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export {default as path} from "./path.js";
^^^^^^
SyntaxError: Unexpected token 'export'
> 1 | import { path } from 'd3-path'
To reproduce:
git clone https://github.com/luucvanderzee/jest-problem.git
cd jest-problem
npm i
npm run test
// The test runs without failure- this is because we're currently still using d3-path#2.0.0
npm uninstall d3-path && npm install d3-path // (upgrade to d3-path#3.0.1)
npm run test
// Now the test fails.
How should I configure jest and/or babel to solve this issue?
EDIT:
I already tried the following (from this page of the jest docs):
Creating a jest.config.js file with the following:
module.exports = {
transform: {}
}
Changing my "test" command from "jest" to "node --experimental-vm-modules node_modules/jest/bin/jest.js"
This gives me another error:
/home/luuc/Projects/javascript/jest-problem/test/test.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import fn from '../src/index.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
I also don't get what is meant by
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
Isn't the problem that the module is not transformed? Would adding an ignore pattern not just lead to the module not getting transformed?

Problem
The error happens because jest does not send the content of node_modules to be transformed by babel by default.
The following output line of npm run test indicates one way to solve the problem:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
Solution
The configuration of jest should be updated in order to instruct it to transform the ESM code present in d3-path dependency.
To do so, add the following to a jest.config.js file in the root directory of the project:
module.exports = {
transformIgnorePatterns: ['node_modules/(?!(d3-path)/)']
}
npm run test runs fine after that.
The transformIgnorePatterns option is documented here.
Edit - including more modules
In order to include all modules starting with d3, the following syntax may be used:
transformIgnorePatterns: ['/node_modules/(?!(d3.*)/)']

TLDR;
transformIgnorePatterns: [
"/node_modules/(?!d3|d3-array|d3-axis|d3-brush|d3-chord|d3-color|d3-contour|d3-delaunay|d3-dispatch|d3-drag|d3-dsv|d3-ease|d3-fetch|d3-force|d3-format|d3-geo|d3-hierarchy|d3-interpolate|d3-path|d3-polygon|d3-quadtree|d3-random|d3-scale|d3-scale-chromatic|d3-selection|d3-shape|d3-time|d3-time-format|d3-timer|d3-transition|d3-zoom}|internmap|d3-delaunay|delaunator|robust-predicates)"
]
For the ones reaching this page after updating recharts dependency, here I found the solution, provided by them.

Related

Jest command not recognized

So i just started learning about Test Driven Developement and as an example i was asked to run the command npm test helloWorld.spec.js in the terminal but i got this error :
> javascript-exercises#1.0.0 test
> jest "helloWorld.spec.js"
'jest' n’est pas reconnu en tant que commande interne
ou externe, un programme exécutable ou un fichier de commandes.
// in english jest isn't recognized as an internal command or external
I'm working on windows and the only thing i have installed is node so what do i have to do?
Choose one of the following methods
1) Install globally
You need to install jest globally:
npm install jest -g
Note: You will have to call it as jest something.spec.js in your cli or specify a test command in your package.json.
2) Install locally
Install jest locally with npm install jest -D.
You can use a script in your package.json called test which would be "test": "jest".
If any of the above don't work, try reinstalling jest.
If it still doesn't work, try removing node_modules and npm cache clean --force and npm install
3) Config file
If you already have jest installed but it's not working, you can use a config file to track files based on regex pattern (you can do a lot more if you check out the docs).
The following part is from the docs:
Jest's configuration can be defined in the package.json file of your project, or through a jest.config.js, or jest.config.ts file or through the --config <path/to/file.js|ts|cjs|mjs|json> option. If you'd like to use your package.json to store Jest's config, the "jest" key should be used on the top level so Jest will know how to find your settings:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
Or through JavaScript:
// Sync object
/** #type {import('#jest/types').Config.InitialOptions} */
const config = {
verbose: true,
};
module.exports = config;
// Or async function
module.exports = async () => {
return {
verbose: true,
};
};
Or through TypeScript (if ts-node is installed):
import type {Config} from '#jest/types';
// Sync object
const config: Config.InitialOptions = {
verbose: true,
};
export default config;
// Or async function
export default async (): Promise<Config.InitialOptions> => {
return {
verbose: true,
};
};
When using the --config option, the JSON file must not contain a "jest" key:
{
"bail": 1,
"verbose": true
}
Regex options
testMatch [array]
(default: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ])
The glob patterns Jest uses to detect test files. By default it looks for .js, .jsx, .ts and .tsx files inside of __tests__ folders, as well as any files with a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It will also find files called test.js or spec.js.
Note: Each glob pattern is applied in the order they are specified in the config. (For example ["!**/__fixtures__/**", "**/__tests__/**/*.js"] will not exclude __fixtures__ because the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after **/__tests__/**/*.js.)
testRegex [string | array]
Default: (/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$
The pattern or patterns Jest uses to detect test files. By default it looks for .js, .jsx, .ts and .tsx files inside of \_\_tests\_\_ folders, as well as any files with a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It will also find files called test.js or spec.js. See also testMatch [array], but note that you cannot specify both options.

Mocha / Webpack: Cannot use import statement outside a module

I'm new to Node and JS Testing. I have a web applications w/ Webpack as a bundler. I have some entry point JS's which are included into the page. The entry points are using module files like this:
export default function() {
...
}
Now I would like to Unit test this module. I have picked up Mocha but it is not critical to me. Could be Jest or anything else.
I wrote a very simple test.js like this. It it not doing anything but tests if the entire setup works:
import foo from '../js/someModuleOfMine'
const assert = require('assert')
describe('Test Suite', () => {
it('should at least run', () => {
assert.equal(true, true)
})
})
executing mocha from CLI gives me this error:
import foo from '../js/someModuleOfMine'
^^^^^^
SyntaxError: Cannot use import statement outside a module
Adhering to some advises I have tired to add "type": "module" to my package.json but it only changed error to something even more obscure:
Error: Not supported
I am definitely missing something obvious but I cannot comprehend what.
Not sure if it will help the OP, but I had the same problem and it was due to typescript. I solved in this way:
install ts-node:
npm install ts-node --save-dev
add the require line in the mocha config (I have it in the package.json, but one can also have it in the .mocharc.json file):
"mocha": {
"spec": "./**/*test.ts",
"ignore": "./node_modules/**",
"require": "ts-node/register/files",
"timeout": 20000
}

Getting typeError: (options.astTransformers || []).map is not a function while running the test suite in Angular

I am getting below error while running jest test cases in Angular. All test suites are failing with this error.
Getting typeError: (options.astTransformers || []).map is not a function while running the test suite in Angular
This solution is for Angular 8/9/10
I would recommend doing these steps:
Uninstall jest-preset-angular
Reinstall jest-preset-angular
Clear jest cache
Retry
If the above solution not working, try installing
npm install --dev ts-jest
Fix this error by removing the following line in the jest.config.js file.
module.exports = {
...
passWithNoTests: true,
projects: '<rootDir>/libs/now-version' // <--- newly added property. should be removed
};
As I found this link on github.
https://github.com/nrwl/nx/issues/3885#issuecomment-706620382
This error started after updating Angular to 11, and when I generate a new lib inside NX and it ends up adding this new line, whenever a new lib is generated, by the CLI
Seems to be a newer version of the package.
In the package.json I changed the jest-preset-angular from "8.3.2" to "8.2.0" and that error went away.
Updating the jest.config.js as below fixed my issue
module.exports = {
displayName: 'AppName',
preset: '../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
},
},
coverageDirectory: '../../coverage/libs/appName',
transform: {
'^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular',
},
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
],
testRunner: 'jest-jasmine2'
};
Jest configuration for Angular can be tricky.
I recommend you use jest-preset-angular which is a library that you will import into your Angular project that will manage the configuration of Jest for Angular.
This may be related to the update of Jest 27 that deprecated astTransformers as string[].
Configure your Angular project to use Jest 26 with jest-preset-angular and you should be fine

jest says cannot import outside a module

I'm attempting make a few functions using the Test Driven Development (TDD)
I am writing in javascript.
checkTransparency(urlString)
maketransparent(urlString)
are two functions of mine I'm trying to test and develop which is located in a file called transcript.js.
These uses the inkscape and graphicsmagick npm. I checked checkTransparent works in some other project of mine, but I'm trying to make sure I can just copy paste this transparent.js into another project and use it elsewhere as well.
My folder structure of the project are the following :
+ node_modules
+ src
--- transparent.js
+ test
--- transparent.spec.js
+ package.json
+ package-lock.json
+ jest.config.js
I am using jest as my test framework.
The problem is when I run jest (or npm test)
I get the following:
FAIL test/transparent.spec.js
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• 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/en/configuration.html
Details:
\\..............\transparent\test\transparent.spec.js:4 <FEW DETAILS OMITTED HERE DELIBERATELY>
import { checkTransparency, makeTransparent } from "../src/transparent"; // const transparent = require("../src/transparent");
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime._execModule (C:/Users/Kjeong/AppData/Local/Yarn/Data/global/node_modules/jest-runtime/build/index.js:988:58)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.862s
Ran all test suites.
my jest.config.js:
module.exports = {
testEnvironment: "node",
moduleDirectories: ["node_modules", "src", "transparent"],
moduleFileExtensions: [
"js",
"json",
"jsx",
"ts",
"tsx",
"node"
],
clearMocks: true,
}
I've tried the following exports to get this thing working:
export function checkTransparency(urlString) { ... }
export function makeTransparent(urlString) {... }
module.exports = {
checkTransparency: checkTransparency,
makeTransparent: makeTransparent,
};
In your package.json, using configuration like following could solve your problem:
{
"name": "<blah blah>",
"version": "1.0.0",
"description": "",
"type": "module",
"scripts": {
"start": "node server.js",
"test": "node --experimental-vm-modules node_modules/.bin/jest"
},
}
If you really want to use import keyword then you probably need to follow these explanations. Otherwise why not just require ?
const { checkTransparency, makeTransparent } = require('../src/transparent')
Hope this helps :)

Uglify SyntaxError: Unexpected token: punc ())

I am trying to use gulp in order to minify a folder containing JS files. However, one of the files has the above error, preventing it from being minified.
I managed to catch and print the error, which I've partially printed here:
JS_Parse_Error {
message: 'SyntaxError: Unexpected token: punc ())',
filename: 'ex.js',
line: 189,
col: 25,
pos: 6482,
stack: Error\n at new JS_Parse_Error (eval at <anonymous> ... )
plugin: 'gulp-uglify',
fileName: '.../js/ex.js',
showStack: false
}
The file in question contains the following, shortened:
function() {
...
$.confirm({
buttons: {
confirm: function() {
$.post('/ajax-handler', {
...
})
.done( function(response) {
var data = filterResponse(response);
if (data['status'] == 'success') {
sleep(1000).then(() => {
* ...
});
sleep(5000).then(() => {
...
});
} else {
console.log('Oops!');
}
})
.fail( function(err, status, response) {
...
});
},
cancel: function() {}
}
});
...
}
I added the "*" above in order to indicate the exact position listed by JS_Parse_Error.
// Update
From the comments ~ #imolit
 v2.0.0 (2018-09-14) - BREAKING CHANGES (link)
Switch back to uglify-js (uglify-es is abandoned, if you need uglify ES6 code please use terser-webpack-plugin).
Original answer before the update...
I hope you can get inspired by this solution which works with webpack. (link below)
Simply teach UglifyJS ES6
There are two versions of UglifyJS - ES5 and ES6 (Harmony), see on git
ES5 version comes by default with all the plugins, but if you install a Harmony version explicitly, those plugins will use it instead.
package.json
"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"
or
npm install --save uglify-js#github:mishoo/UglifyJS2#harmony
yarn add git://github.com/mishoo/UglifyJS2#harmony --dev
Webpack
To use it with webpack install also the webpack plugin
npm install uglifyjs-webpack-plugin --save-dev
yarn add uglifyjs-webpack-plugin --dev
then import the manually installed plugin
var UglifyJSPlugin = require('uglifyjs-webpack-plugin');
and replace it in code
- new webpack.optimize.UglifyJsPlugin({ ... })
+ new UglifyJSPlugin({ ... })
For more webpack info (Installation/Usage) see https://github.com/webpack-contrib/uglifyjs-webpack-plugin#install
npm install uglifyjs-webpack-plugin --save-dev is not enough
The main problem is "uglifyjs-webpack-plugin": "^0.4.6" in webpack's package.json
According to semver, ^0.4.6 := >=0.4.6 <0.5.0. Because of the leading zero, webpack will never use the 1.0.0-beta.2.
So after running npm i -D uglifyjs-webpack-plugin#beta, you need to do one more step which is rm -rf node_modules/webpack/node_modules/uglifyjs-webpack-plugin. Then webpack will pick up the version from node_modules/uglifyjs-webpack-plugin instead of node_modules/webpack/node_modules/uglifyjs-webpack-plugin
Update on 2018-04-18: webpack v4 does not have this issue
Add the babel-preset-es2015 dependency to fix this.
And also add 'es2015' in .babelrc file.
json
{
"presets": ["es2015"]
}
I am having the same issue, i found a great answers here that helped me to reach the the file that was causing the error.
Go to Rails Console and Paste:
JS_PATH = "app/assets/javascripts/**/*.js";
Dir[JS_PATH].each do |file_name|
puts "\n#{file_name}"
puts Uglifier.compile(File.read(file_name))
end
Hope it helps someone!
If you got this error using Grunt (grunt-contrib-uglify) the solution is to install ES6 version of the plugin:
npm install grunt-contrib-uglify-es --save-dev
For me it had nothing to do with Uglify not working correctly, but rather a dependency (in this case empty-promise) that has not been compiled to ES5 yet. As we just imported the raw source file, but babel is only transpiling files outside of node_modules, uglify got confused by the ES6 syntax.
Simply check if any dependency you've recently added might not have a "dist" build.
Add stage-3 to presets in .babelrc file.
{
"presets": [
"stage-3"
]
}

Categories

Resources