Developing test cases for mat-autocomplete feature that customizes customer search

I am currently in the process of writing unit tests for an Angular app, specifically Angular6. One specific component that I am focusing on contains mat-autocomplete functionality. My goal is to ensure that the users are properly filtered based on the input they type in the autocomplete input box. A helpful post that I came across that inspired me can be found here.

Below is a snippet of the code in the spec file:

it('should filter customers', async () => {
  fixture.detectChanges();
  let toggleButton = fixture.debugElement.query(By.css('input'));
  console.log(toggleButton.nativeElement);

  toggleButton.nativeElement.dispatchEvent(new Event('focusin'));
  toggleButton.nativeElement.value = "xyz";
  toggleButton.nativeElement.dispatchEvent(new Event('input'));
  fixture.detectChanges();
  await fixture.whenStable();
  fixture.detectChanges();

  const matOptions = document.querySelectorAll('mat-option');
  expect(matOptions.length).toBe(1); //test fails

})

<mat-form-field >
   <input id="inputCustomer" matInput [matAutocomplete]="auto"  [formControl]="customerFilterControl">
   <mat-autocomplete panelWidth ="450px" #auto="matAutocomplete" [displayWith] = "displayFn" style="width:750px;">
       <mat-option  *ngFor="let customer of filteredOptions | async" [value] ="customer.AccountID + '('+ customer.AccountName + ')'" (onSelectionChange)="onCustomerChange(customer)">
       {{customer.AccountID}} ({{customer.AccountName}})
      </mat-option>
   </mat-autocomplete>
</mat-form-field>
**typescript.ts**
this.filteredOptions = this.customerFilterControl.valueChanges.pipe(
  startWith(''),
  map(value => this._filter(value))
);  

_filter(value:any): any[] {
const filterValue = value.toLowerCase();
return this.customers.filter(function (option) {
  if(option.AccountID.includes(filterValue) || option.AccountName.includes(filterValue)) {
    return option;
   }
});
}

https://i.sstatic.net/VQ4r9.png

Answer №1

Make sure to initialize your options before proceeding

  it('should refine customer search',async () => {
    // Set up the data
    const option1 = {AccountID: 1, AccountName: 'AccountName1'};
    const option2 = {AccountID: 2, AccountName: 'xyz'}
    // Set up the data source
    fixture.component.filteredOptions = of([option1,option2])
    fixture.detectChanges();
    let toggleButton = let toggleButton = fixture.debugElement.query(By.css('#inputCustomer'));
    console.log(toggleButton.nativeElement);

    toggleButton.nativeElement.dispatchEvent(new Event('focusin'));
    toggleButton.nativeElement.value = "xyz";
    toggleButton.nativeElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    await fixture.whenStable();
    fixture.component._filter("xyz");
    fixture.detectChanges();

    const matOptions = document.querySelectorAll('mat-option');
    expect(matOptions.length).toBe(1); //test fails

  })

By doing this, your component will have valid options for selection once autocomplete values are added.

Remember to use the of operator (let me know if it works as I have not tested it) to facilitate the async pipe functionality.

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

JavaScript - Output an undefined value of a property within a function

While the question of checking for null or undefined values has been raised before, I am encountering a unique issue. I have created a function to split a string, which works perfectly. However, when I pass a null or undefined value, the program stops. Ins ...

The 'job' field is not recognized within the 'PrismaClient' type, please check the documentation for correct usage

Currently, I am utilizing Expressjs as a backend along with Prisma for database management and TypeScript implementation. I have been referencing this specific article in my development process. A type error that I am encountering is stated as Property &a ...

Bootstrap causing issues with correct display of div element

I'm having trouble getting my divs to display on the same row. It seems like when I have 2 rows, the button is positioned correctly. However, with only one row, the button ends up on the second row. Here is the current layout: https://i.sstatic.net/L ...

The absence of transpiled Typescript code "*.js" in imports

Here is an example of the code I am working with: User.ts ... import { UserFavoriteRoom } from "./UserFavoriteRoom.js"; import { Room } from "./Room.js"; import { Reservation } from "./Reservation.js"; import { Message } from ...

Is it possible to selectively export certain interfaces within a .d.ts file?

// configuration.d.ts export interface Configuration { MENU_STRUCTURE: Node[]; } interface Node { name: string; } Looking at the snippet above, I am aiming to only export Configuration. However, I noticed that I can also import Node from an ext ...

Angular2 Cascading Animations

I have been working on implementing cascaded animations for a list of elements. Although I successfully applied the state triggers, following the guidelines in the documentation, I am encountering an issue where all element states are being applied simult ...

How do I implement a click event in an item list using Angular 5?

As a novice student delving into Angular 5, I am faced with an issue that may also arise in Angular 2. Currently, I am working on a project where I need to implement a basic search input feature. The idea is to allow users to type in the name of a city an ...

Error: The reference to "global" is undefined and was not caught in the promise

After successfully running my project, I encountered an issue upon installing the aws-sdk package from here. Despite trying to find solutions online, I have been unable to resolve this problem. The error message I am facing is: core.js:1673 ERROR Error ...

Using variables in string interpolation

I have been attempting to showcase a react-table cell in a customized manner: public displayBooksTable() { return <div> <ReactTable data={this.props.books} columns={[{ column ...

Error: The JSON file cannot be located by the @rollup/plugin-typescript plugin

I have recently set up a Svelte project and decided to leverage JSON files for the Svelte i18n package. However, I am facing challenges when trying to import a JSON file. Although the necessary package is installed, I can't figure out why the Typescri ...

Resolve the issue with automatically generating SCSS type definitions (style.d.ts) for Preact within a TypeScript webpack setup

Utilizing webpack with Preact 10.x (nearly identical to React) and TypeScript in the VSCode environment. Following an update from Node version 12 to version 14, there seems to be a problem where *.scss files no longer automatically generate their correspo ...

Customize the position of nodes and their descendants in a d3 tree chart by setting specific x and y coordinates

I am in need of a d3 tree structure that looks like this. https://i.sstatic.net/X6U3u.png There are two key points to understand from the image above: Headers will have multiple parents(wells). I need to be able to drag and drop links connecting w ...

Navigating Angular modules - a different perspective

I am brand new to angular routing and lazy loading modules. ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'login-admin/admin-dashboard' Error: Cannot match any routes. URL Segment: 'login-admin/admin-d ...

An issue has arisen with the TypeScript function classes within the React Class, causing a compile error to be thrown

I am currently in the process of transitioning a React object from being a function to a class. This change is necessary in order to save the state and bind specific functions that I intend to pass to child components. Unfortunately, during compilation, I ...

Implementing error wrapper in typescript to handle failing promises with n retries

I have a wrapper function that calls an async function: function fetchAPI(arg1: number, arg2: number, arg3: string) { return new Promise((resolve, reject) => { try { myFetchFunction(arg1, arg2, arg3).then((r: any) => { if (!r) { ...

Is there a way to achieve region collapsing and expanding using #region / #endregion in TypeScript within Visual Studio Community Edition 2019?

For a while now, we've been utilizing "region collapsing" in TypeScript as shown below: //#region GUI handlers ...code related to handling GUI events... //#endregion This method has functioned well in VS2015 CE and VS2017 CE, with a small "-" or "+" ...

Localization & Internationalization in Angular 6 CLI for enhancing multi-language functionality

Our Application is built on Angular 6 and we are looking to incorporate multilingual support. Please advise on how we can enable localization and internationalization in Angular 6. This pertains specifically to the Angular 6 version. ...

Tips for displaying backend error messages on the frontend

I am facing an issue with returning error messages from the backend to the frontend in my Angular project. The specific requirement is to display an error message when the value of msisdn is not eligible for renewal. Currently, the hardcoded error message ...

Alerts created with the AlertController in Ionic 4 Angular are not displaying the message when the

After creating a reliable alert service for my Ionic 4 project, I encountered an issue when building the release version of the app. Despite functioning perfectly in other environments like "ionic serve" and "ionic cordova emulate", the message part of the ...

Webpack may suggest, "An extra loader might be needed" within a React.js project

I recently created a React project with two separate workspaces, named 'webmail' and 'component'. In the 'component' workspace, I added a small tsx file that I wanted to utilize in the 'webmail' workspace. Below is t ...