Elevate the scope analysis for a function within the Jasmine framework

I have written a few functions within the app component. I am experiencing an issue with increasing coverage in the summary for these component methods.

The test cases are functioning correctly, but some lines are not being accounted for in the coverage summary.

app.component.ts

public initializeA(): void {
    this.flagClone.client = {
        build: null, //string
        name: null, //string
        id: null    //string
    }
}

public initializeB(): FlagResult {
    this.isSearch = false;
    return {
        id: null, //string
        description: null,  //string
        url: null,      //string
        client:{
            build: null, //string
            name: null, //string
            id: null    //string
        }
    };
}

app.component.spec.ts corresponding test cases

const testFlagResult: FlagResult = {
    id: null, //string
    description: null,  //string
    url: null,      //string
    client:{
        build: null, //string
        name: null, //string
        id: null    //string
    }
};
it('should initializeA',() => {
    const mock = spyOn(component,'initializeA').and.returnValue();
    component.initializeA();
    fixture.detectChanges();
    expect(mock).toHaveBeenCalled();
});

it('should initializeB',() => {
    const mock = spyOn(component,'initializeB').and.returnValue(testFlagResult);
    component.initializeB();
    fixture.detectChanges();
    expect(component.isSearch).toBeTruthy();
    expect(mock).toHaveBeenCalled();
});

I'm hoping to see the following block included in the coverage summary:

public initializeA(): void {
    this.flagClone.client = {

public initializeB(): FlagResult {
    this.isSearch = false;

Any insights on where I may be missing out?

Answer №1

If you include a spy, you are not validating the code being spied on. Therefore, using

const mock = spyOn(component,'initializeA').and.returnValue();
means you are skipping testing initializeA, and by using
   const mock = spyOn(component,'initializeB').and.returnValue(testFlagResult);
you are neglecting to test initializeB.

An improved approach would be:

it('should initializeA',() => {
    component.initializeA();
    fixture.detectChanges();
    expect(component.flagClone.client).toEqual({
        build: null,
        name: null, 
        id: null    
    });
});

it('should initializeB',() => {
    const expectedResult = {
        id: null, //string
        description: null,  //string
        url: null,      //string
        client:{
            build: null, //string
            name: null, //string
            id: null    //string
        }
    }

    const res = component.initializeB();
    fixture.detectChanges();
    expect(component.isSearch).toBeTruthy();
    expect(res).toEqual(expectedResult);
});

This approach ensures that your method is actually functioning as intended.

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

The user interface in Angular 7 does not reflect the updated values after subscribing

Upon examining the code provided, it is evident that the UI does not reflect the updated value even though the field is set correctly. I have attempted two different approaches but have not explored the change detection approach as I believe the current c ...

Why does TypeScript assign parameters in the opposite direction when assigning callbacks?

When a function is called with an argument, the argument type is matched to the parameter type. This means that the argument type must be the same as, or more specific than, the parameter type. For example: const foo = (bar: string | number) => { con ...

Implementing Bootstrap 4 in an Angular 9 project without the use of JQuery

Currently, I am actively working on detaching all JQuery dependencies within my Angular project. Most of the dependencies stem from utilizing Bootstrap 4 components. Eliminating dropdowns and removing all instances of data-*** seemed to help in this proc ...

Guide to retrieving static information for forms with the use of reactive forms

I am encountering an issue with my reactive form. When I click the new button, a duplicate section appears but the options in the select field are not visible. Additionally, I receive errors as soon as the page loads: ERROR Error: Cannot find control with ...

How to separate an array of objects into individual arrays using Typescript reduce based on a specific property

I have the following array: statisticsOfScrapDeliveriesItems:[ { supplierId: "0001055404", deliveredFrom: "METALLCO AS", centerId: "C45", materialId: "TS0180", }, { sup ...

The window.Print() function is currently experiencing a glitch in Microsoft Edge (Version 91.0.864.59) when trying to use it for the first time within an Angular 12

If you encounter the issue, please follow these steps using the latest version 91.0.864.59 of the Edge browser: https://stackblitz.com/edit/angular-ivy-zbvzap?file=src/app/app.component.html Click on the print button. Close the print dialog. Click on the ...

How can I upload multiple images in one request using Typescript?

HTML: <div> <input type ="file" (change)="selectFiles($event)" multiple="multiple" /> </div> Function to handle the change event selectFiles(event) { const reader = new FileReader(); if (event.target.files & ...

Exploring TypeScript's Index Types: Introduction to Enforcing Constraints on T[K]

In typescript, we can utilize index types to perform operations on specific properties: interface Sample { title: string; creationDate: Date; } function manipulateProperty<T, K extends keyof T>(obj: T, propName: K): void { obj[propName] ...

Learn how to utilize the "is" status in Postma within your code, even when this particular status is not included in the response

Service.ts Upon invoking this function, I receive a JSON response similar to the following: public signupuser(user: Users): Observable<boolean> { let headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

Facing issues updating the parent state value while using NextJs with React

I recently started working with NextJS and React, and I'm using trpc along with useQuery to fetch a list of users. After fetching the user list, I need to filter it based on the user's name. Below is a snippet of the code I've been working ...

Exploring type definition for function arguments in TypeScript and React

There is a high-order component (HOC) designed to store the value of one state for all input and select elements. The output function accepts arguments ({text: Component, select: Component}). An error is displayed while typing an argument: TS2322: Type &ap ...

When using the makeStyles hook in a function component with React, Material-UI, and Typescript, an Invalid Hook Call error may

I'm feeling lost and frustrated with my current coding issue. Despite following the guidelines in the (javascript) documentation, I keep encountering the dreaded Invalid Hook Call error. My setup includes TypeScript 4.1.2, React 17.0.1, and React Typ ...

Add flexible templates into List element in Ionic version 3

My Progress Being a newcomer to ionic, I successfully created a List component in ionic 3 that retrieves JSON data from the server and displays it as a list layout on specified pages using a list selector. Objective I am looking to showcase various list ...

Ensuring Angular Reactive Forms: Validation for Non-Empty Nested FormArray with Display of mat-error

I'm currently working on a project using Angular's reactive forms and facing a challenge with a nested structure. I need to validate that a FormArray of files within another FormArray is not empty. Each groupFiles can have multiple groups, and ea ...

The Children Element in Next.js and React Context with TypeScript is lacking certain properties

Encountering a mysterious error while trying to implement React's Context API in Next.js with TypeScript. The issue seems to be revolving around wrapping the context provider around the _app.tsx file. Even though I am passing values to the Context Pr ...

Why do optional values of objects remain optional when being checked in an if statement in Typescript?

Recently at work, I encountered this code snippet and was left wondering why Typescript couldn't comprehend the logic behind it. If 'test' in the object can either be undefined or a string, shouldn't it logically infer that within an if ...

Receiving an error when triggering an onclick event for a checkbox in TypeScript

I am creating checkboxes within a table using TypeScript with the following code: generateTable(): void { var table = document.getElementById("table1") as HTMLTableElement; if (table.childElementCount == 2) { for (var x = 0; x < 2; x++) ...

How to add unique elements to an array in Angular without any duplicates

I need help with pushing elements into an array and decrementing the count of it without duplicates in angular. Any assistance would be greatly appreciated ...

Guide to navigating to a specific module within an Angular 2 application directly from the index page

As a newcomer to angular2, I recently obtained a sample login and registration code online. However, when I run the code, it displays the index page instead of the "login" module located within the app folder. Can someone please advise me on how to redire ...

Different varieties of TypeScript's keyof when working with objects

I am grappling with the concept of TypeScript's types when incorporating the keyof type operator on objects. Check out this example: type TypeA = { [k: number]: boolean }; type AKey = keyof TypeA; // ^? type AKey = number type TypeB = { [k: string] ...