So many private functions in Angular 2! Should we unit test them or perhaps make them public?

It's interesting to note that the majority of functions in my Angular 2 application are private. Take a look at this component, which happens to be my largest one - a form with numerous child components.

import {
    Component,
    ViewChild,
    ElementRef,
    EventEmitter,
    Output,
    OnInit
} from '@angular/core';
import {
    FormGroup,
    FormBuilder,
    Validators,
    ControlValueAccessor,
    FormControl,
    AbstractControl,
    ReactiveFormsModule
} from '@angular/forms';
import { ResultService } from '../../../services/result.service';
import { Result, FindRequest } from '../../../models/all-models';
import { HighlightDirective } from '../../../directives/highlight.directive';
import { DistanceUnitsComponent } from './distance-units.component';
import { MultiselectComponent } from 
    '../../../shared/subcomponents/multiselect-find-category.component';
import { MultiselectFindMealTypeComponent } from
    '../../../shared/subcomponents/multiselect-find-meal-type.component';
import { NumberPickerComponent } from './number-picker.component';
import { InputComponent } from '../../../shared/subcomponents/input.component';
import { AreaComponent } from 
    '../../../shared/subcomponents/area-picker.component';



@Component({
    selector: 'find-form',
    templateUrl: 'app/find-page/subcomponents/find-page/find-form.component.html',
    styleUrls: ['app/find-page/subcomponents/find-page/find-form.component.css'],
    providers: [ResultService]
})

export class FindFormComponent implements OnInit {
    @ViewChild('multiselectFindCategory')
    private _multiselectFindCategory: MultiselectComponent;
    @ViewChild('multiselectFindMealType')
    private _multiselectFindMealType: MultiselectFindMealTypeComponent;
    @ViewChild('distanceUnits') private _distanceUnits: DistanceUnitsComponent;
    @ViewChild('numberPicker') private _numberPicker: NumberPickerComponent;
    @ViewChild('areaInput') private _areaInput: AreaComponent;
    @ViewChild('keywordsInput') private _keywordsInput: InputComponent;
    @Output() private _onResultsRecieved:
    EventEmitter<Object> = new EventEmitter<Object>();
    @Output() private _onSubmitted: EventEmitter<boolean> =
    new EventEmitter<boolean>

    private _categoryError: string = 'hidden';
    private _mealTypeError: string = 'hidden';
    private _areaError: string = 'hidden';

    private _findForm: FormGroup;
    private _submitted: boolean = false;
    private _findRequest: FindRequest;

    private _displayMealCategories: boolean = false;
    private _mealSelected: boolean = false;
    private _place: google.maps.Place;

    constructor(private _resultService: ResultService,
                    private _formBuilder: FormBuilder) {}

    ngOnInit() {
        this._findForm = this._formBuilder.group({
            categories: [null, Validators.required],
            mealTypes: [[], this._mealTypesValidator()],
            location: null,
            distanceNumber: null,
            distanceUnit: 'kilometers',
            keywords: null,
        });
    }

...

I'm aiming for best practices here by keeping everything private. Is it possible that this approach is inherent to Angular 2? Because typically in non-Angular apps, public elements are more prevalent. I'm pondering if my code is just highly decoupled since no other components need access to it. It's perplexing because I know there's significant logic that should be tested.

Am I overusing private methods? Or is it sound practice to keep them private? And should I simply focus on unit testing these private functions?

Answer №1

In order to maintain best practices, I recommend avoiding adding prefixes to any elements that are exposed in your template HTML or other components. This aligns with the approach used at our organization as well as the guidelines provided in the official Angular2 documentation.

By keeping everything public, you inadvertently test your private functions as they should be called within your public methods.

For comprehensive testing coverage, consider utilizing tools like Protractor and Selenium to create UI-Tests for a wide range of scenarios.

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

Issue detected in the ngx-joyride package: Error found in ./node_modules/ngx-joyride/assets/images/close.svg

During my build process, I encountered an error with ngx-joyride: ERROR in ./node_modules/ngx-joyride/assets/images/close.svg Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type." <line x1="1" y1=" ...

What is the best way to incorporate infinite scrolling into my Angular carousel implementation?

After following an amazing tutorial, I was able to create a basic carousel using two directives and one component in Angular. However, the current version of the carousel lacks an 'infinite scrolling' mode, which is something I would like to inc ...

Is there a way to determine the position of the highlighted text within a textarea?

Is there a simple way to calculate the position of the selected text within a textarea using vanilla JavaScript or Angular (possibly with a directive)? This is important in order to display a div with a popup above the selected text. Coordinates are need ...

Setting up a Variable with an Object Attribute in Angular

I am attempting to create a variable that will set a specific property of an object retrieved through the get method. While using console.log in the subscribe function, I am able to retrieve the entire array value. However, as a beginner, I am struggling ...

Exploring the similarities between using jQuery AJAX post and Angular

In my current project, I have a legacy application that relies on jQuery and unfortunately cannot incorporate Angular at this time. For one specific task, I need to make an AJAX POST request to consume a web service using jQuery. Interestingly, the same ...

Is using instanceof the most effective method to verify type in Angular?

When working with the model, we import Type1 and Type2. Using the TypeComp variable which is a union of Type1 and Type2. import { Type1, Type2 } from '.'; export type TypeComp = Type1 | Type2; In the some.component.ts file, the selectedData$ obs ...

Updating a label dynamically in Angular

QUESTION: Is there a way to dynamically change the text of a label based on a certain condition? Specifically, I want the label to be blank when I'm on a specific route in my App. CURRENT APPROACH: <RadSideDrawer allowEdgeSwipe=&quo ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

Angular 10: A guide to dynamically highlighting navbar elements based on scrolling position

I am currently working on a single-page application using Angular 10. I have a simple page layout and I want to implement a feature that will highlight the navbar based on the scroll position. How can I achieve this functionality in a single-page applicati ...

Is it possible to interchange the positions of two components in a routing system?

driver-details.component.ts @Component({ selector: 'app-driver-details', templateUrl: './driver-details.component.html', styleUrls: ['./driver-details.component.css'] }) export class DriverDetailsComponent implements OnI ...

The issue with Angular 4 imports not refreshing in a .less file persists

Currently, I am in the process of developing a small Angular project that utilizes less for styling purposes. My intention is to separate the styling into distinct folders apart from the components and instead have a main import file - main.less. This fil ...

Customizing the placeholder text for each mat input within a formArray

I have a specific scenario in my mat-table where I need to display three rows with different placeholder text in each row's column. For example, test1, test2, and test3. What would be the most efficient way to achieve this? Code Example: <div form ...

Having trouble installing Angular CLI using npm command

After diligently following the steps outlined in the documentation here to install the Angular CLI, I encountered an issue. Upon running the command $ npm install -g @angular/cli in an empty directory, I was met with the following error message: npm ERR! ...

Issue with Child Component Loading Once CUSTOM_ELEMENTS_SCHEMA is Added to App Module

One of my components, known as HostComponent, works perfectly fine when set as the startup component in my application. However, I decided to create a new module called AppModule and nested the host component within the app component: import { Component, ...

Managing the lifecycles of extended class instances in Angular 2 - what's the best approach?

The code snippet below is causing an issue for me in Angular 2.4.9: export class MyComponent extends BaseComponent implements OnInit { type = 2; constructor() { super(); } ngOnInit(){ console.log('inited type', this.type) } } ...

Modify the color of the matSnackbar

I'm having trouble changing the snackbar color in Angular using Angular Material. I tried using panelClass in the ts file and adding it to the global css, but the color remains unchanged. Any suggestions on how to resolve this? I am still new to this ...

Exploring the functionality of Array.prototype.includes() in Angular 7 with PhantomJS testing

While testing components in my Angular application, I noticed that unit tests utilizing Array.prototype.includes() are successful in Chrome but fail when executed with PhantomJS. I found some suggestions in the responses to this question related to a simi ...

What causes the component's constructor to be invoked multiple times instead of being efficiently reused by the router?

I came across this interesting article where the writer discusses how the router reuses components to avoid unnecessary DOM modifications: In order to prevent unnecessary changes to the DOM, the router will reuse components when the parameters of the co ...

What could be the reason for Angular 2 not recognizing this valid regex pattern?

The regular expression shown below is considered valid (check here): ^(\+27|27|0)\s?(\d{2})[-\s]?(\d{3})[-\s]?(\d{4})$ Despite its validity, Angular 2 throws the following error: EXCEPTION: Error in ./App class App - i ...

Ways to Access HTTP Request Headers in Angular 6 upon Page Load

Is it possible to retrieve request header information in Angular 6/7 upon application initialization? I specifically require access to header values for security and access management purposes, as these values are set in the headers during the usage of th ...