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

Using Typescript and React to retrieve the type of a variable based on its defined type

Just getting started with Typescript and could use some guidance. Currently, I'm using React to develop a table component with the help of this library: Let's say there's a service that retrieves data: const { data, error, loading, refetc ...

Exploring the capabilities of using the injectGlobal API from styled-components in a TypeScript

I've been attempting to utilize the simple injectGlobal API, but I am encountering difficulties getting it to work with TypeScript. Here is my setup in theme.tsx: import * as styledComponents from "styled-components"; import { ThemedStyledComponentsM ...

Could I potentially pause and wait for a subscription in Angular?

I'm looking to display a list of posts similar to this: Post List In order to indicate which post is favorited by a user, I need to retrieve data from two different collections in my MongoDB database. The ngOnInit function in my post-list.component.t ...

Angular: Handling route segment configuration based on the URL

Consider a situation where you have a URL like /path/path2/path3/123;sdf=df and a predefined routes configuration: { path: 'path', data: { g: 'h' }, children: [ { path: 'path2', data: { c: 'd' }, children: [ { ...

Use bracket notation to verify if a property is undefined

Having some difficulty determining if the property value of an object is undefined when accessed dynamically with bracket notation. Here's a snippet of my code: function toBritishDate(date: Date | string): string { console.log(date) return &qu ...

Discovering the Angular HostBinding feature with parameter capabilities

Within my component, there is a numeric input that determines the width of the component. I need to dynamically set the width based on this input value using classes, as the width calculation relies on Sass variables that may change over time. I have thre ...

Tips on continuously making calls to a backend API until receiving a successful response with status code 200

While working on my Angular project, I have encountered a situation where I need to make calls to a backend API. If the response is not 200 OK, I have to keep calling the API every 30 seconds until I receive a successful response. In Angular, I usually ca ...

Creating an Angular project with two different base-href configurations

Angular CLI: 7.2.3 Node: 10.14.1 OS: darwin x64 Angular: 7.2.2 Currently, my index.html file includes a base href set to <base href="/" /> and the application runs at http://localhost:port/ I am wondering if there is a way for my app to run both at ...

Versatile unit equipped with interactive features

As a newcomer to Angular, I have a project in mind to create a versatile confirmation popup component that can serve multiple purposes. Whether it's for deleting or saving an entry, users will need to confirm the action with a simple popup that includ ...

Interpret information in Angular 2 using Typescript

Just starting with Angular (IONIC) and need help. How can I extract the userId or id from this code? his.response = data. //Looking for guidance on accessing Json keys Response : { "userId": 1, "id": 1, "title": "sunt aut facere repellat providen ...

Using Typescript to overload functions with varying first parameters

I am facing a scenario where I have a parent class that requires a method implementation with either one or two parameters depending on the child class. class MyClass { update(obj: HashMap); update(id: ID, obj: HashMap); update(objOrId: HashM ...

The API endpoint returns a 404 not found error on NextJS 14 in the production environment, while it functions correctly on the local

I am in the process of creating a small website using NEXT JS 14. On my website, there is a contact us page that I have been working on. In the GetInTouch.tsx file, I have the following code: <Formik initialValues={{ ...

How can I use Angular2 to draw a square [input] number of times?

I need to create a specific number of squares within a container using Angular2. Can you please provide me with a straightforward example, preferably utilizing canvas? Currently, I have converted webpack starter for use with Angular: This is the code ins ...

Leverage the power of Angular by configuring a custom webpack setup to

Implementing the CSS modules concept in my Angular app has been a challenge due to conflicts with existing frontend CSS. My project utilizes SCSS, and I am looking for a way for webpack to modularize the CSS generated from SCSS during the final build step. ...

What is the method to incorporate @angular/fire into an Nx Workspace for an Angular project?

Incorporating @angular/fire into my Nx workspace for my Angular application is my current goal. Despite my efforts to adhere to best practices, I have not found any guidance in the official documentation on how to incorporate this library into the wor ...

Issue with Angular 2: Route guard failing to work after browser refresh

Defining these routes in app.module.ts: ... { path: 'mypath', component: MyComponent, canActivate: [RouteGuard] }, { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: '**', redirectTo: '/ho ...

What is the best approach to obtain complete and error methods from the server using BehaviorSubject?

Here is a description of my unique service: @Injectable() export class SettingService { private settings = new BehaviorSubject<any[]>([]); constructor(private http: HttpClient) { this.loadSettings(); } private loadSettings( ...

Tips for adjusting the radio button value similarly to a checkbox in Angular 2 using *ngFor

my checkbox and radio button implementation: <input id="{{k.group_name}}_{{i}}" name="{{k.group_name}}" type="checkbox" class="hide" name="{{k.group_name}}" [value]="m.details" (change)="change($event, m , k.item_ingredient_group_key,false,k.maximum)"& ...

Switching out built-in functions with testdouble.js?

Is it feasible to substitute an internal function in a node.js module with td.replace while using testdouble.js for testing? The internal function involves a DB call, so I prefer not to test it. However, I do want to verify that this function receives the ...

The promise callback in Angular2 is unable to access this

This snippet of code is quite odd, but it resides within a service context: constructor() { gapi.load('client:auth2', this.loadGoogleApi); } private loadGoogleApi() { // Array of API discovery doc URLs for APIs used by the quickstart ...