Angular 13 - Node MaxListener Exceeded Warning - javascript

I updated my application from Angular 12 to 13.3.12. When ran the npm start it compiles and the app is app but I get Node warning when navigating across the application in browser. How to get over this warning?
(node) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
npm start - ng serve -proxyconfig proxy.config.json
proxy.config.json
{
"/test1/*":{
"target": "https://testurl.com",
"seure": false,
"changeOrigin": true,
"logLevel": debug
},
"/test2/*":{
"target": "https://testurl.com",
"seure": false,
"changeOrigin": true,
"logLevel": debug
},
"/tes31/*":{
"target": "https://testurl.com",
"seure": false,
"changeOrigin": true,
"logLevel": debug
}
}

Related

Vue app has compilation error when serve is run from jest-playwright-preset, but works fine otherwise

I'm trying to test a vue.js application with playwright.
If I start the mocked server with npm run serve:mock from the command line, then run playwright using npm run test:playwright (jest -c jest-playwright.config.js), everything works fine.
If I try to combine both and have the server start from jest-playwright-preset (jest-process-manager), I get compilation errors when the development server starts:
Module parse failed: Unexpected token (139:76) File was processed with
these loaders: * ./node_modules/cache-loader/dist/cjs.js *
./node_modules/babel-loader/lib/index.js *
./node_modules/eslint-loader/index.js You may need an additional
loader to handle the result of these loaders.
This is the jest-playwright.config.js:
module.exports = {
rootDir: '.',
testTimeout: 120000,
testMatch: ['<rootDir>/tests/playwright/*.spec.js'],
preset: 'jest-playwright-preset',
testEnvironmentOptions: {
'jest-playwright': {
launchOptions: {
headless: false
},
contextOptions: {
ignoreHTTPSErrors: true,
bypassCSP: true
},
browsers: ['chromium', 'firefox']
}
},
serverOptions: {
command: 'npm run serve:mock',
launchTimeout: 50000,
port: 8080,
debug: true
}
};
Why is there a difference, and how can I fix it?

Error testing Typescript files with Open WC Karma-ESM plugin

I ran the test as sudo, i.e. sudo npm run test
....and it worked. Go figure! Anyone care to venture a guess as to why that would be the case?
I'm using the open web components karma-esm plugin to run tests in my monorepo. But I'm getting an error thrown by headless chrome that there's an unexpected token of '<'. I understand that syntax errors like these can happen when testing typescript files but I'm not sure how to overcome it.
Here's my root package.json test script:
"test": "npx karma start --coverage"
Here's my karma.conf.js file (on the root of the repo so no basepath defined):
const defaultConfig = require('#open-wc/testing-karma/esm-config');
const merge = require('deepmerge');
module.exports = (config) => {
config.set(
merge(defaultConfig(config), {
// define where your test files are, make sure to set type to module
files: [
{ pattern: 'packages/*.tests.ts', type: 'module' },
],
plugins: [
// load plugin
require.resolve('#open-wc/karma-esm'),
// fallback: resolve any karma- plugins
'karma-*',
],
frameworks: ['esm'],
esm: {
babel: false,
nodeResolve: true,
fileExtensions: ['.ts', '.scss'],
customBabelConfig: {
plugins: [
['#babel/plugin-proposal-decorators', { legacy: true }],
['#babel/plugin-proposal-class-properties', { loose: true }],
['css-modules-transform', { extensions: ['.css', '.scss', '.less'] }],
],
presets: [
'#babel/preset-typescript',
],
},
},
coverageIstanbulReporter: {
thresholds: {
global: {
statements: 90,
lines: 90,
branches: 90,
functions: 90,
},
},
},
captureTimeout: 60000,
browserDisconnectTolerance: 3,
browserDisconnectTimeout : 60000,
browserNoActivityTimeout : 60000,
}),
);
return config;
};
These are pretty close to the recommended config except for some coverage thresholds. And here's the output of the command:
START:
28 10 2019 16:40:50.262:WARN [filelist]: Pattern
"/Users/ppepperSandbox/Documents/workspace/test-monorepo/__snapshots__/**/*.md" does not
match any file.
28 10 2019 16:40:50.283:INFO [karma-server]: Karma v4.1.0 server started at
http://0.0.0.0:9876/
28 10 2019 16:40:50.283:INFO [launcher]: Launching browsers ChromeHeadlessNoSandbox with
concurrency unlimited
28 10 2019 16:40:50.286:INFO [launcher]: Starting browser ChromeHeadless
28 10 2019 16:40:50.723:INFO [HeadlessChrome 78.0.3904 (Mac OS X 10.14.6)]: Connected on
socket fmkN7XNEGqz3pMNNAAAA with id 92870419
HeadlessChrome 78.0.3904 (Mac OS X 10.14.6) ERROR
Uncaught SyntaxError: Unexpected token '<'
at node_modules/source-map-support/browser-source-map-support.js:1:1
SyntaxError: Unexpected token '<'HeadlessChrome 78.0.3904 (Mac OS X 10.14.6) ERROR
Uncaught SyntaxError: Unexpected token '<'
at node_modules/source-map-support/browser-source-map-support.js:1:1
SyntaxError: Unexpected token '<'
Finished in 0.245 secs / 0 secs # 16:40:50 GMT-0400 (Eastern Daylight Time)
I know that sometimes if the tsconfig.json file has module set as ES formats then a syntax error can occur. But mine has module set as CommonJS which, I thought, would work. Am I not overcoming this issue correctly? Does anyone know? My tsconfig.json file is below:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"removeComments": true,
"strict": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"baseUrl": "."
},
"include": [
"packages/**/src/**/*.ts",
"declarations.d.ts"
],
"exclude": [
"node_modules"
]
}
Thank you!
I ran the test as sudo, i.e. sudo npm run test
....and it worked. Looks like using sudo with npm is a very, very bad idea. I tried to reset the permissions on these files to make it all better but it didn't work. What am I missing?
sudo chown -R $(whoami) /usr/local/lib/node_modules
sudo chown -R $(whoami) /usr/local/bin
sudo chown -R $(whoami) /usr/local/share

Node modules not being parsed correctly for tests?

I'm working in an application and am trying to add a testing framework to automate testing across the app. I'm using Vue, Electron, TypeScript, and Node and am having trouble getting any test that actually uses components to run. For some reason Jest doesn't seem to want to work with the node modules... I have had very little luck finding anything online that points to ways to fix this.
Anyone with any knowledge on the subject who has any pointers or ideas on how to resolve the issue with importing these node modules while running the tests would be greatly appreciated. I can't imagine that this is impossible to do but there really isn't much I can find through my searches.
Error:
$ npm run test
> mdc#1.0.0 test C:\Users\daniel\Desktop\MDC\mdc
> jest --detectOpenHandles
FAIL src/app/features/mdc-window/mdc-window.component.test.ts
● 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:
C:\Users\daniel\Desktop\MDC\mdc\node_modules\bootstrap-vue\es\components\modal\modal.js:3
import bBtn from '../button/button';
^^^^^^
SyntaxError: Unexpected token import
> 1 | import bModal from 'bootstrap-vue/es/components/modal/modal'
| ^
2 | import bTooltip from 'bootstrap-vue/es/components/tooltip/tooltip'
3 | import throttle from 'lodash.throttle'
4 | import Vue from 'vue'
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
at Object.<anonymous> (src/app/features/mdc-window/mdc-window.component.ts:1:1)
at Object.<anonymous> (src/app/features/mdc-window/mdc-window.component.test.ts:3:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 9.13s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! mdc#1.0.0 test: `jest --detectOpenHandles`
npm ERR! Exit status 1
jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
verbose: true,
testPathIgnorePatterns: [
'/build/',
'/config/',
'/data/',
'/dist/',
'/node_modules/',
'/test/',
'/vendor/'
],
globals: {
'ts-jest': {
tsConfig: './src/app/tsconfig.json'
}
}
}
test.ts
import { expect } from 'chai'
import 'jest'
import { MDCWindowComponent } from './mdc-window.component'
const mdcWindowComponent = new MDCWindowComponent()
describe('Test: Set Title Function', () => {
it('should set the variable title to the passed variable', () => {
const title = 'this is a test'
mdcWindowComponent.setTitle(title)
expect(mdcWindowComponent.title).to.equal(title)
})
tsconfig
{
"compilerOptions": {
"allowJs": true,
"outDir": "./built/",
"sourceMap": true,
"strict": true,
"moduleResolution": "node",
"target": "ES2017",
"experimentalDecorators": true,
"noImplicitAny": false,
"emitDecoratorMetadata": true,
"allowSyntheticDefaultImports": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"esModuleInterop": true,
"lib": ["es2017", "dom"]
},
"include": [
"**/*",
"../types/**/*",
"../../node_modules/bootstrap-vue/**/*",
"../../node_modules/electron/**/*"
]
}
relevant packages
"#types/jest": "^23.3.9",
"jest": "^23.6.0",
"ts-jest": "^23.10.4",
To fix this specific error
SyntaxError: Unexpected token import
I fixed this using the following jest.config.js
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
testEnvironment: 'node',
verbose: true,
moduleDirectories: ['node_modules', 'src'],
modulePaths: ['<rootDir>/src', '<rootDir>/node_modules'],
moduleFileExtensions: ['js', 'ts', 'json', 'node'],
transformIgnorePatterns: ['node_modules/(?!(bootstrap-vue)/)'],
testPathIgnorePatterns: [
'/build/',
'/config/',
'/data/',
'/dist/',
'/node_modules/',
'/test/',
'/vendor/'
],
globals: {
'ts-jest': {
tsConfig: './src/app/tsconfig.json'
},
NODE_ENV: 'test'
}
}
Note
preset: 'ts-jest/presets/js-with-ts',
transformIgnorePatterns: ['node_modules/(?!(bootstrap-vue)/)'],
this seemingly was what helped fix the issue, though if you compare the jest.config.js in this answer to my response i did add a few other options which may also be helpful for others.
A healthy amount of reading on the ts-jest config documentation, jest config documentation, and tsconfig documentation does wonders.

Flow type checking performance in VSCode

I've built a new project using create-react-app and wanted to start it using a static type checking, there are two choices now in market:
TypeScript
Flow
I kind want to go with Flow just because it's also built by Facebook and should(?) have better support for a React project.
So what I'm struggling it is type-checking performance in VSCode. Once I created my project, I ran the following commands:
yarn add -D eslint-plugin-prettier husky prettier pretty-quick babel-eslint eslint-plugin-flowtype flow-bin eslint
Added Airbnb React style: eslint --init
Ran flow init
Installed Flow Language Support
Disabled JavaScript and TypeScript language support as recommended
Added following config to my Workspace settings:
-
{
"flow.useNPMPackagedFlow": true,
"flow.pathToFlow": "${workspaceRoot}/node_modules/.bin/flow"
}
My .eslintrc is as follows:
{
"extends": ["airbnb", "plugin:flowtype/recommended"],
"plugins": ["prettier", "flowtype"],
"parser": "babel-eslint",
"env": {
"browser": true,
"es6": true,
"jest": true,
"node": true
},
"rules": {
"react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
"prettier/prettier": [
"error",
{
"printWidth": 80,
"singleQuote": true,
"useTabs": false,
"tabWidth": 2,
"semi": true,
"bracketSpacing": true
}
]
},
"settings": {
"import/resolver": {
"node": {
"paths": ["src"]
}
}
}
}
However Flow seems to be quite slow on my machine, I have added a simple function to my App.js:
const sum = (a: number, b: number) => a + b;
sum(1, '12323');
And it takes up to 10 seconds to validate my code which is quite a bummer. Is there a way to speed this up?
Maybe it's worth to start with TypeScript and don't bother with Flow?
There are some open issues regarding possible memory leaks and performance related problems with flow, some links below:
https://github.com/facebook/flow/issues/2152
https://github.com/flowtype/flow-bin/issues/70
Both tools are great and have their pros and cons, I would personally recommend to give a try to TypeScript too and perform a comparison yourself.
In my own experience on a large code base I have found TypeScript:
more performant
more types for external libraries
larger community

getting nyc/istanbul coverage report to work with typescript

I'm struggling to get proper coverage with nyc/istanbul for my typescript/mocha/gulp project. I've tried a number of approaches, some of them seem to be unable to use source maps and other fails due to ts-node/tsc errors. My current setup is:
nyc relevant config in package.json
"scripts": {
"test:coverage": "nyc npm run test:unit",
"test:unit": "gulp mocha"
}
"nyc": {
"check-coverage": true,
"all": true,
"extension": [
".js",
".jsx",
".ts",
".tsx"
],
"include": [
"src/**/!(*.test.*).[tj]s?(x)"
],
"reporter": [
"html",
"lcov",
"text",
"text-summary"
],
"report-dir": "docs/reports/coverage"
}
gulpfile.js mocha relevant part
const SRC_DIR = path.join(__dirname, 'src');
const SRC_FILES = path.join(SRC_DIR, '**', '*.[jt]s?(x)');
const TEST_FILES = path.join(SRC_DIR, '**', '*.test.[jt]s?(x)');
const MOCHA_CONFIG = {
src: [
TEST_FILES
],
watchSrc: [
SRC_FILES,
TEST_FILES
],
mocha: {
// compilers: [
// 'ts:ts-node/register',
// 'tsx:ts-node/register'
// ],
require: [
'./tests/setup.js',
'ignore-styles',
'source-map-support/register'
]
}
};
gulp.task('mocha', mocha(MOCHA_CONFIG));
tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"rootDir": "./src",
"outDir": "./build",
"allowJs": true,
"module": "commonjs",
"target": "es5",
"lib": ["es5", "es6", "dom"],
"sourceMap": true,
"inlineSourceMap": false,
"inlineSources": false,
"experimentalDecorators": true,
"noUnusedParameters": true,
"noUnusedLocals": true,
"jsx": "react",
"moduleResolution": "node"
},
"exclude": [
"docs",
"tests",
"**/*.test.js",
"**/*.test.jsx",
"**/*.test.ts",
"**/*.test.tsx",
"tools",
"gulpfile.js",
"node_modules",
"build",
"typings/main",
"typings/main.d.ts"
],
"awesomeTypescriptLoaderOptions": {
"useCache": true,
"useBabel": true
}
}
With the above setup coverage produces results for all the files but they are incorrect for TS files most probably due to source maps not being used (i.e. report shows no coverage for lines which are comments and the numbers seems to be wrong as well).
With a number of variant approaches tried with no success one of the most commonly suggested is to add "require": ["ts-node/register"] to nyc configuration yet then I'm getting errors complaining about i.e. gulpfile.js, docs/reports/coverage/lcov-report/prettify.js and number of other JS files to be not under 'rootDir' which is correct yet it is not clear why ts-node tries to process all the files out of src even if they are excluded in tsconfig.json (still the configuration gets really complex).
I'll appreciate any suggestion which way to go to get proper coverage report for TS files.
Recently I found a satisfiable solution by using "target": "es6" instead of es5 in tsconfig.json's compilerOptions. While changing target directly in tsconfig.json may not be an option as it affects build, the other tip is to use TS_NODE_COMPILER_OPTIONS='{"target":"es6"} which can be added directly in package.json scripts as i.e. :
"test:coverage": "TS_NODE_COMPILER_OPTIONS='{\"target\":\"es6\"}' nyc npm run test:unit",
where test:unit is whatever way being used to run actual tests (in my case just gulp mocha.
NOTE: I've also updated nyc to latest 11.1.0 and ts-node to 3.3.0 as suggested on https://github.com/istanbuljs/nyc/issues/618 thread
I'm not sure this is the same problem but I'll put this here in case it helps future developers...
I wasn't getting any coverage data until I added exclude-after-remap=false to the nyc section of my package.json.
This is listed in the documentation but not in a very prominent way (IMO).
Since a lot of changes broke old working setups I created a verbose example project covering typescript + mocha + nyc supporting proper coverage also for non called files (this is often not included in examples) as well as some unit test examples and quality checks using latest versions.
I had several issues whilst going to mocha 8+ nyc 15+. Maybe it also helps someone else stumbling across it.
https://github.com/Flowkap/typescript-node-template
If you're only interested in coverage check the .ncyrc.yml and mocharc.yml as well as the call config in package.json. VsCode launch configs also included:
.nycrc.yml
extends: "#istanbuljs/nyc-config-typescript"
reporter:
- html
- lcovonly
- clover
# those 2 are for commandline outputs
- text
- text-summary
report-dir: coverage
.mocharc.yml
require:
- ts-node/register
- source-map-support/register
recursive: true
color: true
exit: true
extension:
- ts
- test.ts
test job in package.json
"test": "npm run lint && nyc mocha src test",

Categories