`Measuring Code Coverage in Jasmine Unit Tests`

Looking for assistance with unit testing my simple logger .ts file. Can someone help me fix the unit test?

logging.service.ts

import 'reflect-metadata'; // Required for tsyringe
import { singleton } from 'tsyringe';
import { Category } from 'typescript-logging';
@singleton()
export class Logger {
private logger: Category;
constructor(){
this.logger = new Category('oidc-security-logger');
}
trace(msg: string): void {
this.logger.trace(msg);
}
debug(msg: string): void {
this.logger.debug(msg);
}
info(msg: string): void {
this.logger.info(msg);
}
warn(msg: string): void {
this.logger.warn(msg);
}
error(msg: string, error?: Error): void {
if(error){
 this.logger.error(msg, error);
 } else {
 this.logger.error(msg, null);
 }
 }
 fatal(msg: string, error?: Error): void {
 if (error) {
   this.logger.fatal(msg, error);
 } else {
      this.logger.fatal(msg, null);
   }
  }
 }

I have attempted to complete my unit test using the following method. logging.service.spec.ts

import { Logger } from "./logging.service";    

describe("Logger", () => {    
let loggerMok: Logger;    
beforeEach(() => {
 loggerMok = new Logger();
});

it("should be test logger", () => {
const msg='This is for test';
spyOn(loggerMok,'trace').and.stub();
spyOn(loggerMok,'debug').and.stub();
spyOn(loggerMok,'info').and.stub();
spyOn(loggerMok,'warn').and.stub();
spyOn(loggerMok,'error').and.stub();
spyOn(loggerMok,'fatal').and.stub();
loggerMok.trace(msg);
loggerMok.debug(msg);
loggerMok.info(msg);
loggerMok.warn(msg);
loggerMok.error(msg);
loggerMok.fatal(msg);
expect(loggerMok.trace).toHaveBeenCalled();
expect(loggerMok.debug).toHaveBeenCalled();
expect(loggerMok.info).toHaveBeenCalled();
expect(loggerMok.warn).toHaveBeenCalled();
expect(loggerMok.error).toHaveBeenCalled();
expect(loggerMok.fatal).toHaveBeenCalled();

});
});

The unit test seems to be functioning correctly, but the code coverage score is not being generated.

Answer №1

Consider utilizing the callThrough method over stub. By using stub, the actual implementation is not called, essentially disregarding the function call. For more information on this concept, refer to Method stubs.

With callThrough, the actual implementation is executed, resulting in improved coverage. Here's an example:

it("should be test logger", () => {
const msg='This is for test';
spyOn(loggerMok,'trace').and.callThrough();
spyOn(loggerMok,'debug').and.callThrough();
spyOn(loggerMok,'info').and.callThrough();
spyOn(loggerMok,'warn').and.callThrough();
spyOn(loggerMok,'error').and.callThrough();
spyOn(loggerMok,'fatal').and.callThrough();
loggerMok.trace(msg);
loggerMok.debug(msg);
loggerMok.info(msg);
loggerMok.warn(msg);
loggerMok.error(msg);
loggerMok.fatal(msg);
expect(loggerMok.trace).toHaveBeenCalled();
expect(loggerMok.debug).toHaveBeenCalled();
expect(loggerMok.info).toHaveBeenCalled();
expect(loggerMok.warn).toHaveBeenCalled();
expect(loggerMok.error).toHaveBeenCalled();
expect(loggerMok.fatal).toHaveBeenCalled();

});
});

This particular test case may not be very effective as it only verifies if the functions are called. It might be more useful to spy on new Category and confirm its invocation instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying errors from an API using Angular Material mat-error

I am currently working on a form that includes an email field. Upon saving the form, the onRegisterFormSubmit function is called. Within this function, I handle errors returned by the API - specifically setting errors in the email form control and retrie ...

React Native component that enables users to both input their own text and select options from a dropdown menu as they type

Looking to develop a component that combines Text Input and FlatList to capture user input from both manual entry and a dropdown list. Has anyone successfully created a similar setup? I'm facing challenges in making it happen. Here's the scenari ...

Typescript: organizing nested types within an interface

My goal is to create an interface CountersData based on my JSON data. The challenge lies in the nested id property, which contains an array of nested dictionaries. I want this property to be optional. However, I have not been successful in making it option ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

Is the validity of the expression !args.value || args.value.length true?

After analyzing this segment of code, I noticed an interesting expression: !args.value || args.value.length For instance, consider the following scenario: let v = {}; console.log(!v.value); //outputs true console.log(v.value); //outputs undefined con ...

Is Babel necessary for enabling JavaScript compatibility in my TypeScript React project, excluding Create React App?

This is the webpack configuration for my React project built in TypeScript, module.exports = { mode: 'development', entry: ['./src/main.tsx'], module: { rules: [ { // Rule for ts/tsx files only, no rule for js/js ...

Expanding external type declarations within Typescript

I am currently working with Typescript and the ant design library. My goal is to extend an existing interface by adding a single property. To start, I imported the original interface so you can see the folder structure: import { CollapseProps } from &apo ...

What is the process for adjusting the color of axes in vue-chartjs?

Seeking help on how to adjust the color of the axis in my graph. Has anyone encountered a similar issue before? The chart I'm working with resembles the one shown in the image. Not sure if this issue is related to it being a time graph. Below is the V ...

Issue with NgOnInit not properly subscribing to observable when using mockActivatedRoute in Jasmine test scenarios

Below is a simple component that I have. All necessary imports should be assumed: //my-component.component.ts //imports, decorator, etc. routingNumber: number; ngOnInit() { this.route.params.subscribe( params => { this.routingNumber = +p ...

Need to import Vue component TWICE

My question is simple: why do I need to import the components twice in the code below for it to function properly? In my current restricted environment, I am unable to utilize Webpack, .vue Single File Components, or npm. Despite these limitations, I mana ...

What is the best way to set a value to a decorated property within the constructor of a parent class

I am facing an issue with initializing a decorated property "name" in a User class within the parent class constructor (Base) using Object.assign. The value ends up being "undefined" when the decorator is present, but it works correctly when the decorator ...

React encountered an issue: each child element within a list must be assigned a unique "key" prop

I am feeling a bit puzzled as to why I keep getting the error message: child in a list should have a unique "key" prop. In my SearchFilterCategory component, I have made sure to add a key for each list item using a unique id. Can you help me figu ...

Encountering an error message stating "The variable 'App' is declared but not used" when running the index.tsx function

This React project is my attempt to learn how to use a modal window. The tutorial I've been following on YouTube uses JavaScript instead of TypeScript for their React project. However, I'm facing some challenges. Could you possibly help me ident ...

Transitioning menus in Ionic 2

I followed the instructions in the Ionic 2 menu documentation and tried to display the menu in a specific way: https://i.sstatic.net/zzm8f.png My intention was to have the menu displayed below the content page while keeping the menu button visible. Howe ...

I want to modify a class in Angular 8 by selecting an element using its ID and adjust the styling of a div

Is it possible to dynamically add and remove classes using getElementById in Angular 8? I need to switch from 'col-md-12' to 'col-md-6' when a user clicks on the details icon. I also want to modify the style of another div by setting d ...

"Exploring the world of Angular JS through testing controllers with jasmine

I'm currently facing an issue with my test in the controllersSpec.coffee Angular App code: describe 'Controllers', -> beforeEach -> angular.module 'app' describe 'MainCtrl', -> beforeEach inject ($co ...

Retrieve the output of a function in TypeScript

I'm encountering a challenge with returning a string instead of a function in an object value. Currently, an arrow function is returning an array of objects, and one of them needs to conditionally change a value based on the input value. Here is the ...

Angular 8 does not show the default option in the select tag

When I use the following code snippet: <div style="text-align:center"> <form> <select type="checkbox" name="vehicle1" (change)="onchange()" > <option> 1 </option> <opti ...

Using TypeScript to create a unique object type that is mapped with generics for each key

Suppose I have a type representing an array of two items: a list of parameters and a function with arguments corresponding to the parameters. I've created a handy function to infer the generic type for easy use. type MapParamsToFunction<A extends a ...

What is the best way to set up TypeScript interfaces using predefined string literals to limit the possible data types for shared attributes?

In this scenario, we have two interfaces named A and B with validation and variant properties. The goal is to create an Example object by using only the variant and validation values provided (since field is already defined). However, I encountered an erro ...