Code Coverage Sonar Qube for my React Javascript - javascript

The following is what I have for Coverage for my React JavaScript application. I am getting coverage locally with running npm test, but not reported in SonarQube. Can someone help me with what I am missing?
Gradle
// gradle sonar plugin configuration
apply plugin: 'org.sonarqube'
sonarqube {
properties {
property "sonar.projectName", "${project_name}-${version}"
property "sonar.projectKey", "${project_name}-$version}"
property "sonar.sources", "src/main/java/com/company/app,src/main/webapapp/appName/src"
property "sonar.exclusions", "src/main/webapp/appName/src/assests/**"
// Where to find tests file, also src
property "sonar.tests", "src/main/java/com/company/app,src/main/webapp/appName/src"
// But we get specific here
// We do not need to exclude it in sonar.sources because it is automatically taken care of
property "sonar.test.inclusions", "src/**/*.spec.js,src/**/*.spec.jsx,src/**/*.test.js,src**/*.test.jsx"
// Now specify path of lcov and test log
property "sonar.javascript.lcov.reportPaths", "src/main/webapp/appName/coverage/lcov.info"
//property "sonar.testExecutionReportPaths", "src/main/webapp/appName/coverage-final.json // does not work
sonar-project.properties
# Source
sonar.sources=src
# Where to find tests file, also src
sonar.tests=src
# But we get specific here
# We do not need to exclude it in sonar.sources because it is automatically taken care of
sonar.test.inclusions=src/**/*.spec.js,src/**/*.spec.jsx,src/**/*.test.js
,src/**/*.test.jsx
#sonar.testExecutionReportPaths=coverage/jest/testlog.xml
package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest --coverage",
"eject": "react-scripts eject"
},
"jest": {
"transform":{
"^.+\\.[t|j]sx?$": "babel-jest"
},
"collectCoverage": true,
"testResultsProcessor":"jest-sonar-reporter"
},
"homepage": "./",
"devDependencies": {
"jest": "^24.9.0",
"jest-junit-reporter: "^1.1.0"
},
...... removed for brevity

The jest-sonar-reporter package is old and hasn't been updated in 4 years. It has issues with paths not working as intended and failing to be reported.
I have updated the plugin and republished it under #casualbot/jest-sonar-reporter to fix this functionality as well as add other features for the community.
Ex:
package.json
{
...,
"jest": {
"rootDir": ".",
"testResultsProcessor": "#casualbot/jest-sonar-reporter"
},
"#casualbot/jest-sonar-reporter": {
"suiteName": "jest tests",
"outputDirectory": "coverage",
"outputName": "jest-report.xml",
"uniqueOutputName": "false",
"classNameTemplate": "{classname}-{title}",
"titleTemplate": "{classname}-{title}",
"ancestorSeparator": " › ",
"usePathForSuiteName": "true",
"relativePaths": "true"
}
}
Disclosure: I am the developer of the plugin.

Related

migration-mongo not treated as common js

I have a nodejs server part in my project in which I have defined migre-mongo.
My type in package.json is module. Running the migration leads to
> migrate-mongo up && node node.js
ERROR: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/home/igharib/IdeaProjects/sdx-licence-manager/server/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension. ReferenceError: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/home/igharib/IdeaProjects/sdx-licence-manager/server/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///home/igharib/IdeaProjects/sdx-licence-manager/server/migrate-mongo-config.js:34:1
at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
at async Object.read (/usr/local/lib/node_modules/migrate-mongo/lib/env/config.js:69:30)
And when I change the config extention into csj as recommanded I get file not found!
ERROR: Cannot find module '/home/igharib/IdeaProjects/sdx-licence-
manager/server/migrate-mongo-config.js'
Require stack:
- /usr/local/lib/node_modules/migrate-mongo/lib/utils/module-loader.js
- /usr/local/lib/node_modules/migrate-mongo/lib/env/config.js
- /usr/local/lib/node_modules/migrate-mongo/lib/env/migrationsDir.js
- /usr/local/lib/node_modules/migrate-mongo/lib/actions/init.js
- /usr/local/lib/node_modules/migrate-mongo/lib/migrate-mongo.js
- /usr/local/lib/node_modules/migrate-mongo/bin/migrate-mongo.js Error: Cannot find module '/home/igharib/IdeaProjects/sdx-licence-manager/server/migrate-mongo-config.js'
My package json:
{
"name": "server",
"version": "0.8.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "react-scripts test",
"start": "NODE_ENV=production node app.js",
"start:migrate": "migrate-mongo up && node node.js",
"start:win": "SET NODE_ENV=production && node app.js",
"start:srv": "node index.js",
"dev": "nodemon --watch src/server/ app.js",
"backend:test": "jest server --runInBand --forceExit --detectOpenHandles --verbose",
"backend:test-coverage": "jest server --collect-coverage --runInBand --forceExit --detectOpenHandles --verbose",
"lint:server": "eslint server app.js"
},
"author": "Iman",
"license": "",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-session": "^1.17.2",
"fetch": "^1.1.0",
"jwt-simple": "^0.5.6",
"mongoose": "^5.13.2",
"nodemon": "^2.0.10"
}
}
created migrate config:
// In this file you can configure migrate-mongo
const config = {
mongodb: {
url: "mongodb://localhost:27017",
databaseName: "ldb",
options: {
useNewUrlParser: true, // removes a deprecation warning when connecting
useUnifiedTopology: true, // removes a deprecating warning when connecting
// connectTimeoutMS: 3600000, // increase connection timeout to 1 hour
// socketTimeoutMS: 3600000, // increase socket timeout to 1 hour
}
},
// The migrations dir, can be an relative or absolute path. Only edit this when really necessary.
migrationsDir: "migrations",
// The mongodb collection where the applied changes are stored. Only edit this when really necessary.
changelogCollectionName: "changelog",
// The file extension to create migrations and search for in migration dir
migrationFileExtension: ".js",
// Enable the algorithm to create a checksum of the file contents and use that in the comparison to determine
// if the file should be run. Requires that scripts are coded to be run multiple times.
useFileHash: false,
// Don't change this, unless you know what you're doing
moduleSystem: 'commonjs',
};
module.exports = {config};
How can I solve the problem without changing the type=module?
Node version 16.15.0
Since you are using '"type": "module"', in your migrations config file you should change the last line:
module.exports = {config};
to:
export default config;
That should solve the issue

Why does watchman gives timeout error when using it with react-relay?

I'm using WSL Ubuntu to run a react-relay project, but after installing watchman using brew and trying to run the app in watch mode, watchman gives me the following error(I have run the project using yarn start):
Watchman error: The watchman server reported an error: "watchman::QueryExecError: query failed: synchronization failed: syncToNow: timed out waiting for cookie file to be observed by watcher within 60000 milliseconds: Connection timed out", while executing command: QueryRequest(
"query",
"/mnt/d/Work/Personal/react-relay-tutorial",
QueryRequestCommon {
glob: None,
glob_noescape: false,
glob_includedotfiles: false,
path: Some(
...
I've been trying reinstalling watchman without brew, with brew, the same error I get, nothing on the internet helped...
My package.json file:
...
"scripts": {
"start": "yarn run relay && react-scripts start",
"build": "yarn run relay && react-scripts build",
"relay": "yarn run relay-compiler --watch $#",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"relay": {
"src": "./src/",
"schema": "./src/schema.graphql"
},
...
"devDependencies": {
"babel-plugin-relay": "^13.1.1",
"graphql": "^16.3.0",
"relay-compiler": "^13.1.1"
}
...
relay.config.js file
module.exports = {
// ...
// Configuration options accepted by the `relay-compiler` command-line tool and `babel-plugin-relay`.
src: './src',
schema: './src/schema.graphql',
exclude: ['**/node_modules/**', '**/__mocks__/**', '**/__generated__/**'],
};
.babel.rc
{
"plugins": [
"relay"
]
}
Project structure:
PS: when running the project without any watchman it works just fine

React-Scripts and Jest - No tests found on running npm test

I am testing reducers and storage.
I read the jest tutorial-react manual and it's a little different from mine, but I also found information that "react-scripts test" should also work
package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"dependencies": {
"#testing-library/jest-dom": "^5.16.1",
"#testing-library/react": "^12.1.2",
"#testing-library/user-event": "^13.5.0",
"classnames": "^2.3.1",
"faker": "^4.1.0",
"jest": "^27.4.7",
"miragejs": "^0.1.43",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",
"redux": "^4.1.2",
"seedrandom": "^3.0.5",
"web-vitals": "^2.1.3"
},
"devDependencies": {
"jest-watch-typeahead": "^0.6.5",
"prettier": "^2.5.1"
}
Commands
npm test
npm test --config jest.config.js
npm test --setupFile ./src/setupTests.js
npm test --setupFiles ./src/setupTests.js
Output
Active Filters: filename .\\src\\setupTests.js/
› Press c to clear filters.
Watch Usage
› Press a to run all tests.
› Press f to run only failed tests.
› Press o to only run tests related to changed files.
› Press q to quit watch mode.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press Enter to trigger a test run.
On pressing "a",
No tests found, exiting with code 0
Watch Usage: Press w to show more.
./jest.config.js
// Sync object
/** #type {import('#jest/types').Config.InitialOptions} */
const config = {
setupFiles: ['./src/setupTests.js'],
verbose: true,
};
module.exports = config;
./src/setupTests.js
import '#testing-library/jest-dom/extend-expect';
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
This is what the Jest documentation says about how it finds 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.
Since the setupTests.js filename does not meet this criteria, Jest does not recognize it as a test file. If you rename the file to end with .test.js or move it into a __tests__ folder, Jest should be able to find it and run the test. If you need to keep the filename as is, this default behavior can be changed by setting testRegex in jest.config.js (read more about this setting here).
The setupFiles property in jest.config.js is used for setting up the environment before the tests actually run. The documentation for that setting can be found here, but it doesn't appear to be necessary to do any setup for this case based code you provided.

Problem while Testing ES6 Class with Jest

I'm having a problem making a unitary test with jest over an es6 class. I don't know if the configurations were made properly or if I need some extra package.
This is my file queue.js
export default class Queue {
constructor() {
...
}
//Adds a new elemnt to the queue
method1(element) {
...
}
.
.
.
}
This is my test file
import Queue from "../src/queue";
const myQueue = new Queue();
describe("Queue", () => {
...
...
...
});
This is my .babelrc file
{
"presets": ["es2015"]
}
This is my package.json file. The clean, build and production scripts run all ok, but when I try to run the test, then an error is thrown.
{
"name": "queue",
"version": "1.0.0",
"description": "An implementation of a queue data structure",
"main": "queue.js",
"scripts": {
"test": "jest",
"clean": "rm -dr dist",
"build": "npm run clean && mkdir dist && babel src -s -d dist",
"production": "npm run build && node bin/production"
},
"author": "Osiris Román",
"license": "ISC",
"jest": {
"transform": {
"^.+\\.js$": "babel-jest"
}
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-jest": "^25.4.0",
"babel-preset-es2015": "^6.24.1",
"babel-register": "^6.26.0",
"jest": "^25.3.0"
}
}
This is the error:
Plugin/Preset files are not allowed to export objects, only functions. In /home/usuario/practicing/javascript/queue/node_modules/babel-preset-es2015/lib/index.js
Does someone know how can I solve this problem?
The error you are getting means that one of your presets isn't compatible with the babel version.
Looking at your package.json you are using babel version 6. But both jest and babel-jest use later versions of babel. This causes your es2015 preset not to work correctly.
If you are tied to your current version of babel you can downgrade your jest and babel-jest dependencies to a version that uses older versions of babel:
npm uninstall --save-dev babel-jest jest
npm install --save-dev babel-jest#23.6.0 jest#23.6.0
If not, I would recommend to upgrade your babel version (babel-cli, babel-register and babel-preset-es2015 packages) to newer versions.
If you follow this second path, note that babel-preset-es2015 is deprecated and the use of #babel/preset-env is recommended instead.
I finally found how to solve the problem. I'll share here the configuration If someone else is having the same problem.
This is my file queue.js
export default class Queue {
constructor() {
...
}
//Adds a new elemnt to the queue
method1(element) {
...
}
.
.
.
}
This is my test file
import Queue from "../src/queue";
const myQueue = new Queue();
describe("Queue", () => {
...
...
...
});
I decided to use babel.config.js file insted of .babelrc file. This is the content of this new file.
module.exports = {
presets: [["#babel/preset-env", { targets: { node: "current" } }]],
};
This is my package.json file. The clean, build, dev, production and test scripts run all ok without errors.
{
"name": "queue",
"version": "1.0.0",
"description": "An implementation of a queue data structure",
"main": "queue.js",
"scripts": {
"test": "jest",
"clean": "rm -dr dist",
"build": "npm run clean && babel src -s -d dist ",
"production": "npm run build && node bin/production",
"dev": "npm run build && node bin/dev"
},
"author": "Osiris Román",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.8.4",
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.9.5",
"#babel/register": "^7.9.0",
"babel-jest": "^25.5.0",
"jest": "^25.3.0"
}
}
Thanks to #mgarcia comment I decided to avoid babel-preset-es2015 to use the recommended #babel/preset-env .

Stop Jest from running tests on TS files and only on JS files

I can't get Jest, using the command npm test in my program to stop running tests on my TS files. I only want to run them on JS files.
PASS Views/Shared/Global.unit.test.js (14.83s)
FAIL Views/Shared/Global.unit.test.ts
I've got this in my package.json file:
{
"devDependencies": {
...,
"#types/jest": "^24.0.11",
"jest": "^24.7.1"
},
"scripts": {
"test": "jest"
}
}
I have written the tests in typescript and only want the tests to run the js. I've looked everywhere, but all I find are ways to add support for TS testing. I want it to only run on my .js files.
Anyone had this issue or know a fix?
After several hours of searching and messing with Jest documentation and settings, I finally found how to pick only the files you want Jest to look for. Add the "jest" field to the package.json file settings:
{
"devDependencies": {
...,
"#types/jest": "^24.0.11",
"jest": "^24.7.1"
},
"scripts": {
"test": "jest"
},
"jest": {
"testMatch": [
"**/?(*.)+(spec|test).[j]s?(x)"
]
}
}
This needs to be added to your package.json file. This is in the Jest Docs. In the regex above you need to change the .[jt]s just .[j]s, removing the "t".
or in jest.config.js
module.exports = {
...
testMatch: ["**/?(*.)+(spec|test).js"],
...
};

Categories