Tips for setting ngModel and name attributes in an angular test for a custom component

Just getting started with angular.

I recently developed a custom component that implements the ControlValueAccessor to allow developers to easily access its value. Here's an example of how it can be used:

 <app-date [label]="'Date 2'" name='date1' [(ngModel)]="form.date2"
                                            [hidden]="true"></app-date>

I also created a test for this component:

import {async, ComponentFixture, ComponentFixtureAutoDetect, TestBed} from '@angular/core/testing';
import {FormsModule} from '@angular/forms';
import {BsDatepickerConfig, BsLocaleService} from 'ngx-bootstrap';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';

import {CUSTOM_DATE_CONTROL_VALUE_ACCESSOR, DateComponent} from './date.component';
import {UiOmdModule} from '../ui-omd.module';

const currentDate = new Date();

describe('DateComponent', () => {
  let component: DateComponent;
  let fixture: ComponentFixture<DateComponent>;
  let label;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [],
      imports: [
        FormsModule,
        UiOmdModule
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, CUSTOM_DATE_CONTROL_VALUE_ACCESSOR],
      providers: [
        BsDatepickerConfig,
        BsLocaleService,
        {provide: ComponentFixtureAutoDetect, useValue: true}
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DateComponent);
    component = fixture.componentInstance;
    component.value = currentDate;
    // fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('test default values', () => {
    expect(component.editable).toBe(true);
    expect(component.hidden).toBe(false);
    expect(component.showWeekNumbers).toBe(false);
    expect(component.format).toBe('YYYY-MM-DD');
  });

  it('test component contains a label DOM element', () => {
    label = fixture.nativeElement.querySelector('label');
    expect(label).toBeTruthy();
  });
});

In the above code snippet, there is a test called 'test default values' which accesses the properties of the custom component easily.

The question now arises: How can we provide an ngModel and name for this test?

Answer №1

To facilitate testing of my custom component, I devised a method where I created another component within my test that utilizes the custom component itself. By utilizing the @ViewChild functionality, I am able to access elements within the test environment.

@Component( {
  selector: 'app-poc-criteria-select',
  template: '<app-criteria-select ' +
   ' [(ngModel)]="listaOtdelc" ' +
   ' [allElements]="allElementsForTest"  ' +
   ' name="listaOtdelc" ' +
   ' [elementId]="\'otdelc\'"  ' +
   ' [title]="\'Lista de tabla OTDE de LC\'"  ' +
   ' [brand]="\'LC\'"  ' +
   ' [table]="\'OTDE\'"> ' +
   ' </app-criteria-select> '
})
class CriteriaSelectSpecComponent implements OnInit {
  listaOtdelc;
  isHidden = false;
  allElementsForTest: boolean;
  @ViewChild(CriteriaSelectComponent) componentToTest: CriteriaSelectComponent;

  ngOnInit(): void {
  }
}

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

Convert a Java library to JavaScript using JSweet and integrate it into an Angular project

Just recently, I embarked on my journey to learn TypeScript. To challenge my newfound knowledge, I was tasked with transpiling a Java library using JSweet in order to integrate it into an Angular project. This specific Java library is self-contained, consi ...

In Next.js, the Typescript compiler does not halt when an error occurs

I am looking to incorporate Next.js with TypeScript into my project. I followed the official method of adding TypeScript to Next.js using npx create-next-app --typescript. Everything seemed fine, but when a TypeScript error occurs (e.g. const st: string = ...

The offsetTop property of Angular's nativeElement always returns a value of 0

I am currently working on a menu that will automatically select the current section upon scrolling. However, I am running into an issue where I am consistently getting a value of 0 for the offsetTop of the elements. The parentElement returns a value for of ...

Patience is key as we anticipate the parent component/module loading the data

Just a note: I am aware of the existence of APP_INITIALIZER, but it appears to only work in the top-level module (app.module.ts) of the application. I have a parent component that loads some data: In admin-area.component.ts: ngOnInit(): void { forkJo ...

Display customizable template according to variable

The answer provided for the issue regarding dynamic template generation based on value instead of variable in this thread was really helpful. However, I'm facing challenges in getting it to work. Here's a simplified example: export class A { } ...

One server hosts several Angular applications on an IIS website

Is it possible to host multiple independent angular applications on a single IIS virtual directory? For instance: mysite.com/admin mysite.com/sales mysite.com/inventory The issue arises when hosting with folders as the URLs to inner pages do not ...

What is the solution to the error message "Uncaught TypeError: createTheme_default is not a function"?

While working on my react application with vite, typescript, and mui, I encountered the following error: enter image description here This issue seems to be connected to material ui. Sometimes, deleting the 'deps' folder in '\node_mod ...

What is the best way to retrieve class properties within an input change listener in Angular?

I am new to Angular and have a question regarding scopes. While I couldn't find an exact match for my question in previous queries, I will try to clarify it with the code snippet below: @Component({ selector: 'item-selector&apos ...

Error message: NestJS encountered a problem with Neovim due to an import prefix missing and the inability to load a local module

This issue can be frustrating as it doesn't affect the functionality of the program. However, upon opening a new or existing NestJS application, all imports are highlighted as errors. For instance, in the main.ts file, there are two imports: import { ...

Bringing in outdated libraries into an Angular 4 component

I have a vintage library that I want to integrate into my Angular 4 component. This library is not located in the Node module directory. How can I bring in and utilize this library in my component? ...

After installing Microsoft.AspNetCore.SpaTemplates::*, the Angular template seems to be missing

Today I decided to start using .Net and successfully installed the SDK. Following instructions, I ran the CLI command to install the SPA template: dotnet new --install Microsoft.AspNetCore.SpaTemplates::* Although the command ran without any errors, I co ...

Error: Unable to assign void to parameter type

Encountering TypeScript Error: Argument type (response: Response<DSBMannschaftDTO[]>) => void is not assignable to parameter type ((value:Response<DSBMannschaftDTO[]>) => (PromiseLike<void> | void)) null | undefined | undefined ...

Discovering a solution to extract a value from an Array of objects without explicitly referencing the key has proven to be quite challenging, as my extensive online research has failed to yield any similar or closely related problems

So I had this specific constant value const uniqueObjArr = [ { asdfgfjhjkl:"example 123" }, { qwertyuiop:"example 456" }, { zxcvbnmqwerty:"example 678" }, ] I aim to retrieve the ...

To update the scopes for Firebase GoogleAuthProvider and remove the email scope, while adding only the youtube.readonly scope,

After experimenting with Firebase and Angular 2, I have managed to implement user validation in my app and retrieve YouTube Channel information. Below is the code snippet I am using: return new Promise((resolve, reject) => { let provider = new ...

Subscribe to the service in Angular and make repeated calls within the subscription

What is the most effective way to chain subscriptions in order to wait for a result before starting another one? I am looking for something similar to async/await in Javascript, where I need the result of the first call to trigger the next one. Currently, ...

Following the upgrade to Angular 6, the [WDS] connection disconnects on Internet Explorer after the page has

After upgrading my Angular Project from version 5 to 6, I encountered issues specifically with Internet Explorer 11. Whenever I attempt to load the live dev server on localhost:4200, the login page displays but then immediately disconnects from the live de ...

Is it possible to customize the appearance of a toast notification using Toastr beyond the default settings? If so, what options are available for creating

Working with Angular 9 and ngx-toastr has presented me with an interesting challenge. I am tasked with creating custom toast styles that differ significantly from the default ones provided by toastr. Each toast in the set will have unique border colors, f ...

Variability in determining union types for matched conditional results

In my experience, I have noticed a discrepancy in TypeScript's type inference when dealing with conditional return statements in functions. I have two identical functions, register and register2, outlined below: const register = (step: 1 | 2) => { ...

Organizing Angular and Express Files

I've been researching the best way to structure Angular and Express, reading numerous articles and posts on the topic. Now I'm left wondering - should I share the same node_modules folder for both Angular and Express, or keep them separate? My c ...

Tips for adjusting the angle in SVG shapes

I have designed an svg shape, but I'm struggling to get the slope to start from the middle. Can someone please provide assistance? <svg xmlns="http://www.w3.org/2000/svg" fill="none"> <g filter="url(#filter0_b_1_2556)"&g ...