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

Saving JSON data in a variable or array post subscription: What's the preferred method?

I have been receiving JSON files in the following format: {streetAddress: "Kosterlijand 20", postalCode: "3980", city: "Bunnik", country: "Netherlands"} Although the length of these files varies, the structure always remains the same: {key: "string valu ...

After saving any HTML, SCSS, or TS file, Angular 12 does not compile immediately

Recently I upgraded my Angular project from version 8 to 12 and then migrated to eslint. However, I have encountered an issue where the compilation does not begin immediately after saving a file. There is a delay of approximately 2 minutes before the compi ...

Issues arise when attempting to use the Android KeyUp, KeyDown, and KeyPress events in conjunction with Angular2

I am encountering an issue where I consistently receive a keyCode of 229 in Android Chrome browsers when running either: <input type="text" (keydown)="testKeyCodes($event)"/> <!-- or --> <input type="text" (keyup)="testKeyCodes($event)"/& ...

Inheritance-based type inference

I have created a class hierarchy to manage inheritance in my code. Here is an example of how it looks: class A { clone(): A { return new A() } methodA() { return this.clone() } } class B extends A { clone(): B{ return new B() } ...

Embracing Angular2 - incorporating external modules

Attempting to incorporate the phoenix_js NPM module into my Angular2 app (which was created using the Angular2 CLI) is proving to be a challenge. I keep encountering the error message Cannot find module 'phoenix_js'. Many others have also faced t ...

How can one click the button within the expanded dropdown while hovering over the navigation item in Angular and Bootstrap?

Issue Description: Upon hovering over a navigation item, the dropdown container is displayed but it's not clickable. Desired Behavior: Hovering over a navigation item should display the dropdown container and allow clicking on its contents. Furthermo ...

TSLint warning: Duplicate identifier detected - 'err'

Currently facing an issue with tslint displaying the following error Shadowed name: 'err' Providing the code snippet for reference fs.readdir(fileUrl, (err, files) => { fs.readFile(path.join(fileUrl, files[0]), function (err, data) ...

Pagination problem arises when sorting through items

I am facing an issue with filtering items on different pages of my React website. The problem I encounter is that the filtering functionality only works on the initial page where the data is loaded. Code: CustomersEpolicyPage.tsx import React, {useEffect ...

"Enhance your project with the power of Angular CLI, npm,

I am working on an Angular 2 project built with npm and angular-cli. I want to be able to copy a folder into another folder before every compilation. The goal is to have multiple themes in individual folders, and then select one of those themes using a va ...

Typescript: Dynamic return type determined by argument properties

I have a function that should return two different types based on its argument props. interface IPaginateParams { perPage: number; currentPage: number; isFromStart?: boolean; } interface IWithPagination<Data, TParams extends IPaginateParams = IPa ...

What is the best way to integrate @uirouter in the Angular/sampleapp project?

Having trouble configuring the angular/sampleapp to work with @uirouter. Is the systemjs.config.js file set up incorrectly to include @uirouter? 1) Run npm i -S @uirouter/angular 2) Add the following line to the map section in systemjs.config.js ' ...

Utilize the prototype feature from a versatile source

Can a class with a generic like class Foo<A> {} access A's prototype or use a typeguard on A, or perform any kind of logic based solely on A's type - without being given the class, interface, or instance to Foo's constructor (e.g. when ...

How can I prevent an element from gaining focus after opening a NgbModal?

In the template, I am using a ngForm which is passed as an argument to open a NgbModal: <form #optionsForm="ngForm" noValidate (ngSubmit)="saveOptions()" id="optionsForm"> <div class="modal-body"> <div class="form-group"> < ...

Switching to Next.js

In my Next JS application, I have a div that dynamically displays the currency and price of a product when a user visits a product page. <div className="flex"> <Image src={EuroCurrency} alt="Euro Sign} /> <h1 className=" ...

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...

Retrieving an array of objects through an Angular service

I'm fairly new to Angular and Javascript. Recently, I created an Angular service that fetches an array of users from an HTTP call returning JSON data. While the HTTP call is successful and returns the correct data, I'm having trouble passing this ...

The functionality of React useState seems to be operational for one state, but not for the other

I am currently working on developing a wordle-style game using react. Within my main component, I have implemented a useEffect that executes once to handle initialization tasks and set up a "keydown" event listener. useEffect(() => { //The getWor ...

Creating an interface that extends the Map object in TypeScript to maintain the order of keys

After learning that the normal object doesn't preserve key order in TypeScript, I was advised to use Map. Nevertheless, I'm struggling to figure out how to assign values once I've declared the interface. Take a look at my approach: Coding ...

Error Message: "Unable to locate module for Angular 5 UI Components packaging"

In the process of developing UI Components to be used in various web projects throughout the company, we are aiming to publish these components as an npm package on our local repository. It is crucial for us to include the sources for debugging purposes. F ...

Trouble arises when using Wijmo's valueChanged event and data binding in Angular 2

As I was working on the following code snippet that triggers a function when the user modifies the wj-input-time value: @Component({ selector: 'my-app', template: '<wj-input-time [step]="1" (valueChanged)="test()"></wj-inpu ...