How to implement healthcheck service of Angular Web App

Hi,

We have an Angular web app (with a backend in Java SpringBoot).

Need to build a health check service, which tests that all its services are up and working and shows the status to the users.

Is it possible to build that service as a unit test, which calls several other unit tests (testing a few existing web services - get/post) using Jasmine/Karma or Playwright? Can we integrate that in the app, so user clicks a button, it runs and returns/displays the result in the app as binary or a list of binaries (per service)?

If not, what would be a better approach?

Please advise. Any code sample?

Any help is very appreciated,

Oleg.

1 Like

Yes, it is possible to build a health check service as a unit test in Angular using Jasmine and Karma or Playwright. You can write several unit tests that call the existing web services (get/post) and test their responses. You can then run these tests as a suite using Karma or Playwright and display the results to the user in the app as a binary or a list of binaries (per service).

Here’s a sample code for a health check service using Karma and Jasmine:

scss

describe('Health Check Service', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [HealthCheckService]
    });
  });

  it('should test service 1', inject([HealthCheckService], (service: HealthCheckService) => {
    // Write code to call service 1 and test its response
    expect(response).toBe(expectedResponse);
  }));

  it('should test service 2', inject([HealthCheckService], (service: HealthCheckService) => {
    // Write code to call service 2 and test its response
    expect(response).toBe(expectedResponse);
  }));

  // Add more tests for other services as needed
});

You can then integrate this health check service in the app by creating a button that, when clicked, runs the suite of tests and displays the results to the user.

Wow, very interesting! But how can I run that service/tests from web app? I mean, there should be some Jasmine or Karma API call (equivalent on “ng test hcservice”?
Also, how can user then see the results, is there some Jasmine port? or maybe how to get the results in JSON, so I can integrate the view in my app? And what if I need to run it in monitor mode (say, every minute)?

1 Like

@olegkon
In order to run the tests from your Angular web application, you can use the Karma command line interface (CLI). The Karma CLI provides a way to run tests from the command line. You can run the health check tests by calling karma run healthcheck.

To display the results to the user, you can capture the output from the Karma run and display it in your Angular application. You can use the Karma API to obtain the test results in JSON format, which you can then display in your Angular application.

Here’s an example of how you can obtain the results in JSON format using the Karma API:

const Karma = require('karma').Server;
const server = new Karma({
  configFile: __dirname + '/karma.conf.js',
  singleRun: true
}, function(exitCode) {
  console.log('Karma has exited with ' + exitCode);
  process.exit(exitCode);
});

server.on('run_complete', function(browsers, results) {
  console.log(results);
});

server.start();

If you need to run the health check tests in monitor mode (e.g. every minute), you can set the Karma configuration to run in autoWatch mode and use a task scheduler such as cron or Windows Task Scheduler to run the Karma command on a set schedule.

Very interesting! (sorry, I was on business trip for a few days, only saw that post yesterday night)

I need to kick that healthcheck service spec from inside Angular app (on button click). How to do it?

Also, in Jasmine how do I call from healthCheckServiceSpec service1.test1, …test2, test3… or maybe call service1.runAllUnitTests?

Not sure about Karma exit code. I probably need an array of binaries as a result (showing if each service is up - when all its tests pass - or not). And if one of the services fail - show which test(s) fail.

1 Like

@olegkon
To call the health check service endpoint from inside the Angular app on a button click, you can use Angular’s HttpClient module to send an HTTP request to the endpoint. Here’s an example:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-health-check',
  templateUrl: './health-check.component.html',
  styleUrls: ['./health-check.component.css']
})
export class HealthCheckComponent {

  healthCheckResults: string[];

  constructor(private http: HttpClient) { }

  runHealthCheck() {
    this.http.get<string[]>('/healthcheck').subscribe(
      data => {
        this.healthCheckResults = data;
      },
      error => {
        console.log('Health check failed', error);
      }
    );
  }
}

This code sends an HTTP GET request to the /healthcheck endpoint and subscribes to the response. The response is an array of strings, one for each web service being checked, indicating if the service is up or down.

To call the web service unit tests from the health check service, you can use HttpClient to send an HTTP request to the endpoint of each web service unit test. However, I would recommend against this approach as it can be slow and add unnecessary overhead to the health check service.

Instead, I suggest that you use a testing framework like Jasmine to execute the unit tests and report the results to the health check service. You can write a custom Jasmine reporter that sends the test results to the health check service endpoint. Here’s an example:

import { CustomReporterResult } from 'jasmine';
import { HttpClient } from '@angular/common/http';

class HealthCheckReporter {
  constructor(private http: HttpClient) {}

  jasmineStarted(suiteInfo: jasmine.SuiteInfo): void {
    // Initialize health check results
  }

  specDone(result: CustomReporterResult): void {
    // Update health check results with the status of the spec
  }

  jasmineDone(): void {
    // Send health check results to the health check endpoint
    this.http.post('/healthcheck', healthCheckResults).subscribe(
      data => {
        console.log('Health check results sent successfully', data);
      },
      error => {
        console.log('Health check failed', error);
      }
    );
  }
}

This code defines a custom Jasmine reporter that updates the health check results with the status of each spec and sends the results to the health check endpoint when all specs are done.

To run the Jasmine tests and generate the health check results, you can use the jasmine-core package in combination with the Karma test runner. Here’s an example of a Karma configuration file that runs the Jasmine tests and generates the health check results:

module.exports = function(config) {
  config.set({
    frameworks: ['jasmine'],
    reporters: ['progress', 'custom'],
    customReporters: [
      {
        reporter: HealthCheckReporter,
        url: 'http://localhost:8080/healthcheck'
      }
    ],
    files: [
      // Add your unit test files here
    ],
    browsers: ['Chrome'],
    singleRun: true
  });
};

This code configures Karma to use the Jasmine framework, the progress reporter for the console output, and the custom reporter for the health check results. The custom reporter is configured to use the HealthCheckReporter class and send the health check results to the http://localhost:8080/healthcheck endpoint.

The health check results can be an array of booleans or objects indicating the status of each web service being checked. If all tests for a web service pass

If all tests for a web service pass, you can set the corresponding status to true. If one or more tests fail, you can set the corresponding status to false and add information about the failed tests.

Here’s an example of what the health check results might look like:

[
  { serviceName: 'Service1', status: true },
  { serviceName: 'Service2', status: false, message: 'Test1 failed' },
  { serviceName: 'Service3', status: true }
]

In this example, Service1 and Service3 are up and running (all their tests passed), while Service2 is down (at least one test failed). The message field provides additional information about the failed test.

Finally, to display the health check results in the Angular app, you can modify the runHealthCheck method to update the UI with the results. Here’s an example:

runHealthCheck() {
  this.http.get<any[]>('/healthcheck').subscribe(
    data => {
      this.healthCheckResults = data;
      // Update the UI with the health check results
      this.healthCheckResults.forEach(result => {
        const el = document.createElement('div');
        el.textContent = `${result.serviceName}: ${result.status ? 'UP' : 'DOWN'}`;
        if (!result.status) {
          const errorEl = document.createElement('div');
          errorEl.textContent = result.message;
          el.appendChild(errorEl);
        }
        document.body.appendChild(el);
      });
    },
    error => {
      console.log('Health check failed', error);
    }
  );
}

This code updates the healthCheckResults property with the results returned by the health check endpoint and creates a new div element for each web service being checked. The text content of the div element shows the name of the service and its status (either “UP” or “DOWN”). If a service is down, an additional div element is created to show the error message. The div elements are appended to the body element. You can modify this code to display the health check results in a more user-friendly way (e.g. using a table or a list).

1 Like

All that is great and fascinating. I have a fair amount of writing unit tests using Jasmine for my Angular web apps, but don’t have much experience with advanced Karma and Jasmine Reports. By the way, can the jasmine-reporters be useful for me? Sorry, it doesn’t allow me to place a link from npmjs site.
And where does the custom Jasmine report will go in my app, is that a service or auxiliary class?
What I am not sure is where/how my CheckHealth service should call service1.test1-2-3 (and service2.test1…3) and grab its results. Should it be done from HealthCheckService or HealthCheckServiceSpec? Please clarify.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.