Rupesh Tiwari
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- layout: post title: Publishing Merged Code Coverage Report for Nx Workspace in Azure CI Pipeline date: 2021-02-01 18:55 -0500 subtitle: Learn how to publish Nx Monorepo multiple angular projects code coverage as single report in Azure CI Pipeline description: Learn how to publish Nx Monorepo multiple angular projects code coverage as single report in Azure CI Pipeline cover-img: https://i.imgur.com/hiQZ0BG.png cover_image: https://i.imgur.com/6gxkEV3.jpg thumbnail-img: https://i.imgur.com/6gxkEV3.jpg share-img: https://i.imgur.com/6gxkEV3.jpg tags: 'nx,devops,tutorial,beginners' last_modified_at: published: true sitemap: true comments: true social-share: true excerpt_separator: "<!--more-->" --- # Merge and Publish Code Coverage for Nx Workspace in Azure CI Pipeline [![hackmd-github-sync-badge](https://hackmd.io/bohA65OyRBmNYjadH1LqhQ/badge)](https://hackmd.io/bohA65OyRBmNYjadH1LqhQ) ![](https://i.imgur.com/6gxkEV3.jpg) If you are working on [Nx Monorepo](https://nx.dev/) workspace and have many angular projects. And if you are using Azure CI/CD Pipeline then you might aware that there is no inbuilt azure task which will combine all of your code coverage xml. Therefore, the only workaround is you must consolidated all code coverage reports in one and publish that merged one only. ## What is Code Coverage Report in Azure CI Pipeline >Code coverage helps you determine the proportion of your project's code that is actually being tested by tests such as unit tests. To increase your confidence of the code changes, and guard effectively against bugs [Learn More...](https://docs.microsoft.com/en-us/azure/devops/pipelines/test/review-code-coverage-results?view=azure-devops) Reviewing the code coverage result helps to identify code path(s) that are not covered by the tests. This information is important to improve the test collateral over time by reducing the test debt. ![](https://i.imgur.com/LlgbXvN.png) You can see at file level in azure pipeline ![](https://i.imgur.com/7FuBO8Z.png) ## Azure devops does not merge multiple code coverage reports ![](https://i.imgur.com/nrjxLDu.png) At present, the code coverage reporting functionality provided by this task is limited and it does not merge coverage data. If you provide multiple files as input to the task, only the first match is considered. If you use multiple publish code coverage tasks in the pipeline, the summary and report is shown for the last task. Any previously uploaded data is ignored. [Learn more...](https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/test/publish-code-coverage-results?view=azure-devops ) However, Azure Devops supports merging multiple test results and display out of the box. Check [Publish Test Results Nx Monorepo Angular Azure Pipelines](https://hackmd.io/ChTI9iFXQXGdlQAWrcqrKA) article to learn more. ![](https://i.imgur.com/oEUkpIZ.png) ## Installing Cobertura-merge npm package At this time Azure Pipeline only support showing code coverage using **Cobertura** or **JaCoCo** coverage formats only. I am using Cobertura in order to publish code coverage. [cobertura-merge](https://www.npmjs.com/package/cobertura-merge) is the npm package is a Utility to merge multiple cobertura xml files into one. I will use this npm package to merge my all code-coverage files. ![](https://i.imgur.com/Huz8YLq.png) ## Installing Glob npm package We have nested code-coverage files so, I want to search all of the file path. Therefore, I am installing [glob npm package](https://www.npmjs.com/package/glob) to do that for me. Glob npm package: Matches files using the patterns the shell uses, like stars and stuff. ![](https://i.imgur.com/I9fjMZK.png) ## Folder structure of multiple code coverage files Since I have a Nrwl.Nx monorepo which has angular apps and libs. And when I run the test using `--codeCoverage=true` then it creates the `cobertura-coverage.xml` files. Read [Publish Code Coverage Nx Monorepo Angular in Azure Pipelines] to learn how to publish code coverage to azure pipeline. Notice, I have coverage files from applications (apps) and libraries (libs) ![](https://i.imgur.com/FaaC9hS.png) ## Finding all Coverage File paths We need to get the path of each `cobertura-coverage.xml` file. Lets create a `merge-codecoverage.js` JavaScript file to search all xml files we will use `glob` npm package. ```javascript= const glob = require('glob'); const path = require('path'); const targetDir = path.resolve(__dirname, '../../coverage'); glob(targetDir + '/**/*.xml', {}, (err, files)=>{ console.log(files) }) ``` ![](https://i.imgur.com/HTtZNTz.png) ```shell= [ "c:/Full Stack Master/Fullstackmaster COURSES/Mono Repo Course/temp/nx-monorepo-angular/coverage/apps/cutepuppies-admin/cobertura-coverage.xml", "c:/Full Stack Master/Fullstackmaster COURSES/Mono Repo Course/temp/nx-monorepo-angular/coverage/apps/cutepuppies-client/cobertura-coverage.xml", "c:/Full Stack Master/Fullstackmaster COURSES/Mono Repo Course/temp/nx-monorepo-angular/coverage/libs/branding/logger/cobertura-coverage.xml", ] ``` ## Debugging JavaScript in VS Code Read this article to learn [How to debug Node.JS Code in VsCode](https://hackmd.io/2OykEQiaR6aOEGv9eEHDnA) ## Move All Cobertura Coverage Xml to Merge Folder Install [fs-extra](https://www.npmjs.com/package/fs-extra) which will help us to copy all of the coverage file in `merge` folder and then we will user [cobertura-merge](https://www.npmjs.com/package/cobertura-merge) npm package to crate single `merged-cobertura-coverage.xml` file. ![](https://i.imgur.com/XYWAJIf.png) ```javascript= function copyCodeCoverageToMergedFolder() { const coverageDir = path.resolve(__dirname, '../../coverage'); const mergedDir = path.join(coverageDir, '/merged'); const files = glob(coverageDir + '/**/*.xml', { sync: true }); files.forEach((f, i) => { const x = `${path.basename(f)}-${i}.xml`; // creating unique file name fs.copySync(f, `${mergedDir}/${x}`); }); } ``` ![](https://i.imgur.com/xCyymoJ.png) ## Merging All Cobertura Coverage Xml to Single Report We will create `merged-cobertura-coverage.xml` which is combined of all of the report files. In order to merge all of them we need below script. ```shell= npx cobertura-merge -o merged-cobertura-coverage.xml package1=cobertura-coverage.xml-0.xml package2=cobertura-coverage.xml-1.xml package3=cobertura-coverage.xml-2.xml ``` Running the cobertura-merge script ![](https://i.imgur.com/dbWBJuM.png) Merged file created inside the merged folder ![](https://i.imgur.com/6ZfMhQw.png) Merged cobertura-coverage.xml file ![](https://i.imgur.com/F8zDEc4.png) Here is the JavaScript for merging code coverage files. ```javascript= function mergeCodeCoverage() { const files = glob(mergedDir + '/**/*.xml', { sync: true }); const packages = files .map((f, i) => `package${i + 1}=${path.basename(f)}`) .join(' '); const script = `cobertura-merge -o merged-cobertura-coverage.xml ${packages}`; execSync(script, { stdio: [0, 1, 2], cwd: mergedDir, }); } ``` ## Updating Azure Pipeline to publish code coverage Use below task to publish merged code coverage report in azure pipeline. ```yaml= # Publish Code Coverage Results - task: PublishCodeCoverageResults@1 enabled: false displayName: Code Coverage inputs: codeCoverageTool: 'Cobertura' summaryFileLocation: '$(Build.SourcesDirectory)/coverage/merged/merged-cobertura-coverage.xml' condition: | and( succeeded(), not(contains( variables['COMMANDS'], '"test":[]' )) ) ``` ## Identify How many projects are affected I changed the logging.service.ts in branding service. Which is used by both apps. Run `nx affected:dep-graph --base=main` ![](https://i.imgur.com/X6P4NiW.png) ## Running azure pipeline for nx monorepo Now lets run the azure pipeline and see if we can see the 3 projects code coverage is shown in merged fashion. See 3 tests are running in azure pipeline ![](https://i.imgur.com/quNbF0h.png) publishing code coverage in azure pipeline ![](https://i.imgur.com/kAyhXao.png) Notice it published the code coverage report for all 3 projects. ![](https://i.imgur.com/KaGBGjL.png) ## Excluding files from code coverage I want to exclude the src folder root files from code coverage. We dont want to show `test.ts` or `polyfills.ts` coverage report. ![](https://i.imgur.com/7AAnzIh.png) Go to `workspace.json` file and identify your project names and in the `test` configuration insert code coverage exclude file list like below screenshot. ```json= "codeCoverageExclude": [ "apps/cutepuppies-client/src/test.ts", "apps/cutepuppies-client/src/polyfills.ts" ], ``` ![](https://i.imgur.com/JGmLJ1s.png) Now run `nx run cutepuppies-client:test --codeCoverage=true` Now notice we do not have `src` folder files code coverage. ![](https://i.imgur.com/6zHAjd0.png) Lets do this exclude for all of our project's test configuration. ## Showing Project Names in Merged Code Coverage Report Notice, I have code coverage from below projects. ![](https://i.imgur.com/OTTjEXI.png) I want to show the project names in the Code Coverage Report of Azure pipeline. Therefore, we will update the JavaScript code to put correct project name per code coverage file in our merged code coverage xml file. Like Below: ![](https://i.imgur.com/3fSOEx6.png) I need to generate & run below `cobertura merge` script to create correct merged code coverage file with project names. ```shell= npx cobertura-merge -o merged-cobertura-coverage.xml cutepuppies-admin=apps-cutepuppies-admin-cobertura-coverage.xml cutepuppies-client=apps-cutepuppies-client-cobertura-coverage.xml branding-logger=libs-branding-logger-cobertura-coverage.xml branding-ngmaterial=libs-branding-ngmaterial-cobertura-coverage.xml customers-users=libs-customers-users-cobertura-coverage.xml sales-puppies=libs-sales-puppies-cobertura-coverage.xml sales-puppy-editor=libs-sales-puppy-editor-cobertura-coverage.xml ``` Change the merge code coverage in JavaScript ```javascript= function mergeCodeCoverage() { copyCodeCoverageToMergedFolder(); const files = glob(mergedDir + '/**/*.xml', { sync: true }); const packages = files .map((f, i) => { const fileName = path.basename(f); const projectName = projects.filter((p) => fileName.search(p) > -1).pop(); return `${projectName}=${fileName}`; }) .join(' '); const script = `npx cobertura-merge -o merged-cobertura-coverage.xml ${packages}`; execSync(script, { stdio: [0, 1, 2], cwd: mergedDir, }); } function copyCodeCoverageToMergedFolder() { fs.emptyDirSync(mergedDir); const files = glob(coverageDir + '/**/*.xml', { sync: true }); files.forEach((f, i) => { const x = f.split('/coverage/')[1].replace(/\//g, '-').split('/').pop(); fs.copySync(f, `${mergedDir}/${x}`); }); } ``` ## Running Azure pipeline & Showing Nx Monorepo All Projects Code Coverage Now you must [call the above JavaScript from `azure-pipelines.yml` file](https://hackmd.io/QiDKOk2RTKee1Y822ceSYA). :runner: Run your pipeline ![](https://i.imgur.com/5TKEEo0.png) :100: Showing Code Coverage percentages ![](https://i.imgur.com/pr8leAN.png) :hugging_face: Notice now we see our code coverage per application and the correct file names. ![](https://i.imgur.com/I2ldTr2.png) ![](https://i.imgur.com/cqwnG3N.png) --- ## Do You Want to become full stack developer? :computer: If you want to become full stack developer and grow your carrier as Lead Developer/Architect. Consider subscribing to our full stack development training programs. We have monthly membership plans and you will get unlimited access to all of our video courses, slides, source code & Monthly video calls. - Please visit www.fullstackmaster.net/pro to subscribe to All Access PRO membership. - Please visit www.fullstackmaster.net/elite to subscribe to All Access ELITE membership. You will get everything from PRO plan. Additionally you will get access to monthly live Q&A video call with Rupesh and ask doubts and get more tips and tricks. >You bright future is waiting for you so visit today www.fullstackmaster.net and allow me to help you to board on your dream software architect/lead role. --- ### :sparkling_heart: Contact Details: Say :wave: to me! * Rupesh Tiwari * www.rupeshtiwari.com * :email: <fullstackmaster1@gmail.com> * Founder of www.fullstackmaster.net :mortar_board: * [<img src="https://i.imgur.com/9OCLciM.png" width="295" height="65">](http://www.fullstackmaster.net)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully