Nx 20, Angular 18, Jest, and SonarQube Integration Guide

Ekrem Koçak
4 min readDec 3, 2024

--

This article explains how to integrate SonarQube into a project that uses Nx, Angular, and Jest.

1. Create an Nx Workspace

Run the following command to create a new Nx workspace:

npx create-nx-workspace

2. Generate a Library (Optional)

If your project involves multiple applications or libraries, Create a library to simulate;

npx nx generate @nx/angular:library --directory=libs --name=abc --no-interactive --dry-run

3. Update package.json test Script

Modify the scripts section in your package.json file as shown:

"scripts": {
"start": "nx serve",
"build": "nx build",
"test": "nx run-many --target=test --all --skip-nx-cache --verbose"
}

4. Configure Jest for Coverage

Update the jest.preset.ts file:

const nxPreset = require('@nx/jest/preset').default;
module.exports = {
...nxPreset,
collectCoverage: true, // Enable coverage reports
};

5. Run Tests

Execute the following command to generate a coverage report:

npm run test

This will create a coverage folder.

6. Set Up SonarQube

a. Install SonarQube Using Docker

Run the commands below to set up SonarQube:

docker pull sonarqube
docker run -d --name sonarqube -p 9000:9000 sonarqube

b. Access the SonarQube Interface

Go to http://localhost:9000/. Log in using:

  • Username: admin
  • Password: admin

Create a new project via Projects → Create New Project.

7. Add SonarQube Dependencies

Install the required packages:

npm install -D sonar-scanner
npm install -D jest-sonar-reporter

8. Create sonar-project.properties

In the root directory of your Nx project, create a sonar-project.properties file with the following content:

sonar.projectKey=myproject
sonar.host.url=http://localhost:9000
sonar.login=YOUR_SONARQUBE_TOKEN

sonar.sources=src/,libs/
sonar.inclusions=**/*.ts,**/*.scss,**/*.html
sonar.exclusions=**/node_modules/**,**/*.spec.ts
sonar.tests=src/,libs/
sonar.test.inclusions=**/*.spec.ts
sonar.typescript.tsconfigPath=tsconfig.json
sonar.typescript.lcov.reportPaths=coverage/lcov.info
sonar.javascript.lcov.reportPaths=coverage/lcov.info
sonar.sourceEncoding=UTF-8

Replace YOUR_SONARQUBE_TOKEN with the token generated in SonarQube.

9. Update jest.preset.ts for SonarQube

Add SonarQube-related configurations:

const nxPreset = require('@nx/jest/preset').default;
module.exports = {
...nxPreset,
collectCoverage: true,
coverageReporters: ['html', 'lcov', 'text'], // Add lcov
testResultsProcessor: 'jest-sonar-reporter', // Add reporter
};

10. Merge Coverage Files

By default, Jest generates separate coverage files for each library or application. SonarQube expects a single lcov.info file. To solve this, create a merge-coverage.js file in the root directory:

const fs = require('fs');
const path = require('path');

// Directories containing coverage reports
const coverageDirs = [
'./coverage/libs/core',
'./coverage/my-project', // Add additional project directories
];

// Output path for the merged file
const mergedCoveragePath = './coverage/lcov.info';

// Merge logic
let mergedData = '';

coverageDirs.forEach((dir) => {
const lcovPath = path.join(dir, 'lcov.info');
if (fs.existsSync(lcovPath)) {
const data = fs.readFileSync(lcovPath, 'utf8');
mergedData += data + '\n';
}
});

fs.writeFileSync(mergedCoveragePath, mergedData, 'utf8');
console.log(`Coverage reports merged into ${mergedCoveragePath}.`);

11. Update Test Script

Modify the test script in package.json to include coverage merging:

"scripts": {
"start": "nx serve",
"build": "nx build",
"test": "nx run-many --target=test --all --skip-nx-cache --verbose && node merge-coverage.js"
}

Run the tests:

npm run test

Verify that the coverage folder now contains the merged lcov.info file.

12. Run SonarQube Scanner

Run the SonarQube scanner to upload metrics:

npx sonar-scanner

Alternatively:

node_modules/sonar-scanner/bin/sonar-scanner

Visit http://localhost:9000/projects to view your project metrics.

GitHub Repository

Conclusion

This guide offers a clear and effective approach for integrating testing and maintaining code quality in Nx-based Angular projects using Jest and SonarQube. The provided steps ensure smooth integration of coverage reports and SonarQube analysis, specifically designed for multi-library or multi-application projects.

--

--

No responses yet