Jest with angular unable to turn on coverage because of es6 - javascript

I'm trying to set up an angular project to work with jest. So far it works with the following config
// jest.config.js
module.exports = {
// other stuff
preset: "jest-preset-angular",
setupFilesAfterEnv: ["<rootDir>/setup-jest.ts"],
globalSetup: "jest-preset-angular/global-setup",
globals: {
"ts-jest": {
tsconfig: "<rootDir>/tsconfig.spec.json",
stringifyContentPathRegex: "\\.html$",
useESM: true,
},
},
};
And the following in my setup-jest.ts
import 'jest-preset-angular/setup-jest';
import './jest-global-mocks';
Problem is that as soon as I introduce any code that brings in an ES module, it blows up (even though I've tried following the ESM support page on the jest-preset-angular docs). So far, I've just dealt with this by finding alternative packages. But when I try to turn on --coverage, I get this.
import { __decorate } from "tslib";
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import { TestBed } from '#angular/core/testing';
> 2 | import { AppModule } from './app.module';
| ^
3 | import { APP_BASE_HREF } from '#angular/common';
4 |
5 | describe('The app module', () => {
I've tried dissecting jest-preset-angular and extracting the settings that seem like they should apply to projects using ES6, which has led me to making these changes:
// jest.config.js
module.exports = {
// other stuff
setupFilesAfterEnv: ["<rootDir>/setup-jest.ts"],
transformIgnorePatterns: ["/node_modules/(?!tslib)"],
transform: {
"^.+\\.(ts|html|svg)$": "jest-preset-angular",
},
extensionsToTreatAsEsm: [".ts"],
globals: {
"ts-jest": {
tsconfig: "<rootDir>/tsconfig.spec.json",
stringifyContentPathRegex: "\\.html$",
useESM: true,
},
},
};
And now its failing on the core angular mjs files
/Users/benwainwright1/repos/ng-budget/node_modules/#testing-library/angular/fesm2020/testing-library-angular.mjs:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import * as i0 from '#angular/core';
^^^^^^
SyntaxError: Cannot use import statement outside a module
This is even more confusing for me because as far as I can see
the transform key doesn't specify .mjs, so .mjs files should be left alone
I'm using node v16 and jest v28, which should automatically treat .mjs files as modules

Related

vitest crypto.randomUUID() is not a function

vite.config.ts
import { sveltekit } from '#sveltejs/kit/vite';
const config = {
plugins: [sveltekit()],
test: {
include: ['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
environment: 'jsdom',
globals: true,
setupFiles: 'src/setupTests.ts'
}
};
export default config;
src/setupTests.ts
import '#testing-library/jest-dom/extend-expect';
MyComponent.svelte
onMount(() => {
postElementId = crypto.randomUUID();
...
});
Error
TypeError: crypto.randomUUID is not a function
I've got a component that uses the crypto api to create a random id and works as intended, but when I want to test it, everytime I do this error pops up, any help is appreciated!
Just checking, did you:
import crypto from 'node:crypto';
at some point?
My vitest error was window.crypto.randomUUID() is not a function.
So, I added setupFiles to vite.config.js
test: {
setupFiles: [
'./test/_setup/globalSetup.js'
],
...
Then, in globalSetup.js file I added these 2 lines:
import {randomUUID} from 'node:crypto';
window.crypto.randomUUID = randomUUID;
And it seems to have done the trick.

run pm2 with ES modules

How can i use pm2 in combination with a package based on ES Module (type:"module")
I looked into similar Questions without any useful help (some say it does not work on windows, but i am using linux)
I always receive the error:
Error [ERR_REQUIRE_ESM]: require() of ES Module /opt/app/server/lib/src/index.js not supported.
0|any| Instead change the require of index.js in null to a dynamic import() which is available in all CommonJS modules.
My ecosystem.config.js looks like:
const os = require('os');
module.exports = {
apps: [{
port : 3000,
name : "any",
script : "lib/src/index.js",
watch : true,
instances : os.cpus().length,
exec_mode : 'fork',
env: {
NODE_ENV: "production",
}
}]
}
index.js is a ES module using "import" syntax. How can i tell pm2 that is should use this way of importing
To achieve this you can create an intermediary CommonJS module which loads your application from ESModule. It's possible with import function available in commonJs modules.
This is how might this look:
ecosystem.config.js
lib/src/index.cjs CommonJS entry point (for PM2).
lib/src/index.js ESModule entry point (for ESM-compatible tools).
lib/src/app.js Application code.
ecosystem.config.js:
const os = require('os');
module.exports = {
apps: [{
port : 3000,
name : "any",
script : "lib/src/index.cjs", // 👈 CommonJS
watch : true,
instances : os.cpus().length,
exec_mode : 'fork',
env: {
NODE_ENV: "production",
}
}]
}
lib/src/index.js:
import {app} from './app.js'
app()
lib/src/index.cjs:
import('./app.js') // 👈 There is import function available in CommonJS
.then(({app}) => {
app()
})
lib/src/app.js:
import {hello} from './greet.js'
export function app() {
console.log(hello('World'))
}
lib/src/greet.js:
export function hello(name) {
return `Hello, ${name}!`
}
renaming ecosystem.config.js to ecosystem.config.cjs worked for me

NextJS: Can't use absolute imports in external libraries when using experimental.externalDir

Having the following folder structure of my monorepo that uses nextjs, lerna and npm workspaces:
packages
next-js-app
pages
index.tsx
tsconfig.json
ui-library
src
components
dropdown.tsx
index.ts
utils.ts
tsconfig.json
package.json
lerna.json
tsconfig.json
I want to import the ui-library in the next-js-app such as:
// packages/next-js-app/pages/index.tsx
import { UiLibrary } from '#workspaceName/ui-library'
I allowed it by adding externalDir: true to experimental key in the next.config.js inside the next-js-app:
module.exports = {
...
experimental: {
externalDir: true
}
...
}
Problem
The import works, but inside the packages/ui-library/src/components/dropdown.tsx there's a line:
// packages/ui-library/src/components/dropdown.tsx
import { helperFunction } from 'utils'
meaning that I want to import helperFunction from packages/ui-library/src/utils.ts.
When running next dev script from packages/next-js-app I get the following error:
wait - compiling...
error - ../ui-library/src/components/dropdown.tsx:3:0
Module not found: Can't resolve 'utils'
1 | ...
2 | ...
> 3 | import { helperFunction } from "utils"
4 |
5 | const Dropdown = () => {
6 | const onClick = (event) => {
While if I run the ui-library separately it will be ok with using absolute paths in imports.
Question
How can I make absolute imports work in this case?
The way I fixed it in my case, was adding aliases to my webpack config (inside next.config.js file)
module.exports = {
...
experimental: {
externalDir: true
}
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
'utils': path.resolve('../../packages/ui-library/src/utils'),
// ^ defined all paths used within my external UI library
},
}
}

Automating umd export to esm import in Rollupjs

I have a bit perplexing case about default exports currently.
node --version -> v16.1.0, rollup -> 2.50.4, via #open-wc/building-rollup ^1.10.0 and update separately.
In bn.js there seem to be UMD export as far I understand as
if (typeof module === 'object') {
module.exports = BN;
} else {
exports.BN = BN;
}
BN.BN = BN;
BN.wordSize = 26;
then it is imported in other file BigNumber.ts as
import _BN from "bn.js";
import BN = _BN.BN;
However, in my build I receiver error
[!] Error: 'default' is not exported by node_modules\bn.js\lib\bn.js, imported by node_modules#ethersproject\bignumber\lib.esm\bignumber.js
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module
node_modules#ethersproject\bignumber\lib.esm\bignumber.js (11:7)
9: import _BN from "bn.js";
10: var BN = _BN.BN;
11: import { hexlify, isBytes, isHexString } from "#ethersproject/bytes";
^
12: import { Logger } from "#ethersproject/logger";
13: import { version } from "./_version";
Error: 'default' is not exported by node_modules\bn.js\lib\bn.js, imported by node_modules#ethersproject\bignumber\lib.esm\bignumber.js
All right! I read from https://nodejs.org/api/esm.html and https://github.com/evanw/esbuild/issues/532 and https://github.com/rollup/rollup/issues/3514#issuecomment-640020081 (+ https://github.com/webpack/webpack/issues/11014#issuecomment-641550630 and https://sokra.github.io/interop-test/#rollup), for a good measure for lengthy, discussion about the issue (and other less authoritative places) and then I think I could perhaps just patch manually bn.js and its package.json in node_modules.
So off I go, copy-paste bn.js to bn.esm.js and alter its export to
export default { BN }
and add
"module": "lib/bn.esm.js"
And indeed, it succeeds! Now there is however other includes with a similar issue.
This is puzzling, since in rollups.config.js I have
plugins: [
resolve({ browser: true, preferBuiltins: true }),
commonjs()
]
which I thought does something similar already. Am I mistaken? Could something like tsconfig.json settings interfere with the process? If it matters, the project/configuration that produces this is at https://github.com/veikkoeeva/erc1155sample/blob/main/web/rollup.config.js#L25.

Rollup with d3 plugin : reference is not defined

I'm quite new using rollup to make custom d3 build. I'm trying to use the d3-annotation plugin but when the build is done, I get an error in my console:ReferenceError: d3Dispatch is not defined
In the builded file, it seems that all the property like d3Dispatch, d3Selection, etc. aren't "translated". The require lines disappear too (which is probably normal).
Here is rollup config file:
import { queue } from "d3-queue";
import { event, select, selectAll } from "d3-selection";
import { scaleLinear, scaleIdentity } from "d3-scale";
import { drag } from "d3-drag";
import { json } from "d3-request";
import { annotation, annotationCalloutCircle } from "d3-svg-annotation";
export {
queue,
event,
select,
selectAll,
scaleLinear,
scaleIdentity,
drag,
json,
annotation,
annotationCalloutCircle
}
Which it used with a gulp task:
gulp.task('d3-rollup', function() {
return rollup({
entry: 'js/custom.d3.js',
plugins: [
babel(),
nodeResolve({ jsnext: true }),
commonjs(),
rollup_uglify()
]
}).then(function(bundle) {
return bundle.write({
format: 'umd',
moduleName: 'd3',
dest: 'js/d3.min.js'
});
});
});
I just can't get what is wrong. Do I need to import another property ? Have you an idea ?
This was a bug in the es6/jsnext/module setup for the package.json of the project. It has been resolved in versions 1.6.0 and up.

Categories

Resources