Unit Testing with Angular: Testing the setValueControl function

I am currently in the process of writing unit tests for a straightforward function that assigns controls to various values.

fillFormAssociazioneVeicolo() {
    if (this.aaa) {
      setValueControl(
        this.aaa.targaTelaio,
        this.form.get('targaTelaio')
      );
      setValueControl(
        this.aaa.tipoVeicolo,
        this.form.get('tipoVeicolo')
      );
      setValueControl(
        this.aaa.tipoVeicolo?.descrizione,
        this.form.get('descTipoVeicolo')
      );
      setValueControl(
        this.aaa.nomeCognome,
        this.form.get('nomeCognome')
      );
      setValueControl(
        this.aaa.codiceFiscale,
        this.form.get('codiceFiscale')
      );
    }

This is the purpose of the setValueControl function:

export function setValueControl(
  value: any,
  control: AbstractControl | null,
  disable: boolean = true
) {
  if (control) {
    control.setValue(value);
    if (disable) disableControl(control);
  }
}

I attempted the following approach, however it did not yield the expected result:

it('can fillFormAssociazioneVeicolo', () => {
    component.riempiFormAssociazioneVeicolo();
    expect(setValueControl(component.associazioneVeicolo?.tipoVeicolo,component.form.get('tipoVeicolo')));
  });

Answer №1

One thing to note is that setValueControl may not be ideal for unit testing because it relies on the presence of the "disableControl" function. A well-testable function should ideally be independent of external functions and pure in nature...

export function setValueControl(
  value: any,
  control: AbstractControl | null,
  disable: boolean = true
) {
  if (control) {
    control.setValue(value);
    if (disable) control.disable();
  }
}

To test this function, you can use spyOn (assuming jasmine is being used) with a mock object to verify its behavior:

let controlMock = {
  setValue:(a) => {},
  disable: () => {}
}

const setValueSpy = spyOn(controlMock, 'setValue')
const disableSpy = spyOn(controlMock, 'disable')

setValueControl("hello", controlMock)

expect(setValueSpy).toHaveBeenCalledWith("goodbye");
expect(disableSpy).toHaveBeenCalled();

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

What causes the object type to shift away from 'subscribe'?

Currently, I am facing an issue with retrieving a Coupon object from the server using a REST API in combination with Angular. The problem arises when I attempt to access the 'subscribe' method - within the 'subscribe', the object is of ...

Issue with Angular 12 SSR: Translation file paths are not being properly retrieved

In my Angular project, I have a file located at src->app->lang-translate->lang-translate.module.ts that is trying to access files from other locations as shown below: {prefix: "../../assets/translate/Pages/header/", suffix: ".json"}, {prefix: "../../assets ...

Is there a way for me to modify a value in Mongoose?

I have been attempting to locate clients by their ID and update their name, but so far I haven't been successful. Despite trying numerous solutions from various sources online. Specifically, when using the findOneAndUpdate() function, I am able to id ...

Why did the homepage load faster than the app.component.ts file?

I am facing an issue where the homepage is loading before app.component.ts, causing problems with certain providers not working properly due to import processes not being fully completed. Despite trying to lazy load the homepage, the console.log still sho ...

Tips for styling the value of a control in an Angular Reactive Form

What is the best way to format a value in an Angular Form Control? For example, if I have a date field returned from a database with seconds and milliseconds included, how can I format it to show only day, month, year, etc. similar to using the date pipe? ...

TS2339: The attribute 'size' is not present on the 'string' data type

Within my Typescript file, I have the following line: return stringToValidate.length <= maxLength; Despite the code executing without issues, an error is displayed: TS2339: Property 'length' does not exist on type 'string'. I am cu ...

Adding an external JavaScript library file to a specific component in Angular 7 is a straightforward process. Let's walk through the

As a beginner in Angular framework, I've encountered an issue while working on creating a custom HTML template using Angular version 7. My template consists of various pages like home, about, product, etc. Specifically, on the home page, I am trying t ...

Disabling a Field in Angular While Preserving its Value

Hey there, late night folks! I have a quick question about Angular. I'm working with a form that includes a specific field where I set the value using patchValue, but I also need to disable this field. The issue is that after disabling it, the value i ...

Creating a declaration file for a library's entry point involves outlining the structure and types

I have developed an npm library that is made up of several ES6 modules, which are then consolidated into a single js file. The directory structure looks like this: src main.ts one.ts two.ts three.ts types index.d.ts index.ts The index.ts fil ...

Creating a Fixed HeaderToolbar in FullCalendar React

I am currently working on customizing the FullCalendar React component and I am looking to incorporate a sticky headerToolbar. My main objective is to have the header along with its toolbar remain fixed at the top of the calendar, even when users scroll th ...

Syncing data between local storage and a remote server using Ionic5 provider

I've been considering implementing a data provider that could store a duplicate of the backend data locally for quick access. I believe this concept is referred to as mirroring or something similar. Nevertheless, it must be synchronized and updated r ...

Tips for ensuring a program pauses until an observable is completed within an Angular application

Currently, I am working on a project using Angular. I encountered a situation where a call to the backend is made using an observable to fetch products. Below is an example of how the code appears: getProducts () : Product[] { this.http.get<[]>(this ...

The AgGridModule type does not feature the property 'ɵmod'

Recently, I decided to update my application from Angular 12 to Angular 13. The tools I am using include webpack 5, ag-grid 15.0.0, and ag-grid-angular 15.0.0. While the compilation process goes smoothly for the app, I encountered an issue when trying to l ...

Error: The 'update' property cannot be found on the specified type

Starting a new AngularCli project and need to incorporate a Gauge chart. I've used the code from StackBlitz Angular Gauge Chart Example When I run ng serve --open, I encounter the following errors in the terminal: ERROR in src/app/gauge/gauge.comp ...

Is it feasible to select which modules to be loaded into the application?

Looking for a solution to my problem outlined in the title. For example, I am tasked with creating two separate versions of an app - one for France and one for the UK. In some areas, they require completely different implementations. Is it feasible to sw ...

Guide to combining an Angular 2 (angular-cli) application with Sails.js

I am looking to integrate the app created using angular-cli with Sails.js. My background is in PHP, so I am new to both of these frameworks. What are the steps involved in setting them up together? How can I execute commands like ng serve and/or sails li ...

Enhance autocomplete functionality by incorporating a left icon feature for text fields within the autocomplete component

I have a component with autocomplete functionality that displays tags Autocomplete with tags and I am trying to add a left icon, but only the right icon is functioning correctly. Current Issue When I add a left icon, it shows up but prevents the renderi ...

Conceal components using routing in Angular2 release candidate 1

I have a request regarding certain elements that are to be displayed on all pages except the login page. I am considering using either ngIf or the hidden property of the elements to hide them when the user is on the login page. Here is what I have attempt ...

Cheerio fails to retrieve items from the specified directory

My main goal with cheerio is to scrape the titles from this IMDb ranking: Despite following the documentation and specifying the exact HTML path for the titles, I am getting back random and confusing objects like: 'x-attribsNamespace': [Object ...

The ng2-image-viewer does not support the newest versions of Angular (11 and above)

Encountering an issue with ng serve: Error message: ERROR in node_modules/ng2-image-viewer/index.d.ts:3:22 - error NG6003: Appears in the NgModule.exports of SharedModule, but could not be resolved to a NgModule, Component, Directive, or Pipe class. This ...