Exploring methods to retrieve the inner HTML content from <mat-option> during a typescript unit test

This is the HTML block:

<mat-select ...>
  <mat-option
    *ngFor="let option of options"
  >
    {{ option.text }}  // I am looking to retrieve this data.
  </mat-option>
</mat-select>

When writing my typescript unit test, I encountered difficulties in querying the content of option.text. Despite trying multiple approaches, such as the ones below, I was unable to achieve the desired results:

// Preparation.
const matSelect = fixture.debugElement.query(By.directive(MatSelect)).nativeElement;
matSelect.click();
fixture.detectChanges();

// Attempted queries resulted in null errors:
fixture.debugElement.query(By.directive(MatOption)).nativeElement.textContent

fixture.debugElement.query(By.css('.mat-option')).nativeElement.textContent

fixture.debugElement.query(By.css('mat-option')).nativeElement.textContent

Answer №1

Using By.directive may not yield the desired results when trying to select an item from a mat-select dropdown.

const matSelect = fixture.debugElement.query(By.directive(MatSelect)).nativeElement;
matSelect.click();
fixture.detectChanges();

Consider using:

const matSelect = fixture.debugElement.query(By.css('mat-select')).nativeElement;
matSelect.click();
fixture.detectChanges();

To retrieve text content, you can use the following code snippet:

    const text = fixture.debugElement.query(By.css('mat-option')).nativeElement.textContent;

    expect(text.trim()).toEqual("Steak");

Check out this stackblitz demo for reference.

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

A cautionary message about the React / TypeScript serviceWorker Update function and steps to troubleshoot

Whenever I attempt to run npm run build, an error pops up that says: Failed to compile. src/serviceWorker.js Line 38:36: Array.prototype.map() expects a value to be returned at the end of arrow function array-callback-return // Update a service work ...

The build script does not execute during the creation of a Node.js and React application in Visual Studio

I am currently following a detailed guide on setting up Visual Studio 2019 to develop a Node.js-React application. The link to the guide can be found here: https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-nodejs-with-react-and-jsx?view=vs ...

The type 'contextPaneTitleText' argument cannot be assigned to the parameter type 'key of RemoteConfig'

I am encountering an issue when using the following code snippet: const contextPaneTitleText = useFeature("contextPaneTitleText").asString(); This code is resulting in an error message: Argument of type '"contextPaneTitleText" ...

The angular code does not ensure that the height of the HTML element is set to

After downloading the angular getting-started source code from https://angular.io/start, I ran npm install and ng serve without any issues. As I started customizing the code to create my own app, I encountered an obstacle: my app renders with a height lim ...

What is the best way to set a value for an undeclared control in a reactive form?

I have not declared an email control in the HTML file, but I have declared it in my form group. I want to set the email value that is receiving in the customers to the email control. <form class="form-row" [formGroup]="form"> ...

Implementing a click event on a button within an infowindow on Google Maps in Angular

I've successfully set up the infowindow on my Google Maps and I'm looking to include a button inside it. Here's the code I used: InitializeMap() { this.map = new google.maps.Map(document.getElementById('map'), { zoom: 10, cen ...

The type 'ClassA<{ id: number; name: string; }>' cannot be assigned to the type 'ClassA<Record<string, any>>'

One requirement I have is to limit the value type of ClassA to objects only. It should also allow users to pass their own object type as a generic type. This can be achieved using Record<string, any> or { [key: string]: any }. Everything seems to be ...

Go through each item in the array and change its properties

When retrieving data from the database, I receive the following information: "Data": [{ "mainData": [{ "_id": ObjectId("5ab63b22d012ea2bc0bb7e9b"), "date": "2018-03-24" }], "files": [ { "_id": ObjectId("5ab63b22d012ea2bc0bb7e9d"), ...

Having trouble getting Sass extending to work in a basic scenario?

Here we have a simple example of Sass code, an Angular 2 component that accesses the Sass code, and the rendered HTML. However, there seems to be an issue with the blueBig span element in the last part. As someone new to Sass, I am not sure why this basic ...

What methods are available to rapidly test Firebase functions?

While working with Typescript on firebase functions, I have encountered challenges in testing and experimenting with the code. Despite using the Lint plugin to identify errors without running the code, I am struggling to run the code and view the output. ...

Tips for importing font files from the node_module directory (specifically otf files)

We cannot seem to retrieve the fonts file from the node module and are encountering this error message. Can't find 'assets/fonts/roman.woff2' in 'C:\Projects\GIT2\newbusinessapp\projects\newbusinessapp\src ...

Simple Steps to View Angular Logs in Terminal

Upon initializing my Angular project, I utilized the npm start command to kickstart the application. The console.log() function displays logs exclusively in the browser console window. Is there a way to view these logs in the terminal window? ...

RXJS - Hold off until the shop is fully stocked

Here's a function I have that needs some adjustment: combineLatest([this.contact$, this.account$]).pipe( map((res) => {contacts = res[0], account = res[1]})).subscribe() I am facing an issue where the contact$ selector is sometimes empty. If it ...

Preventing errors from interrupting valueChanges in Angular

Within my Angular 6 application, I am encountering an issue with certain rxjs operators. The problem arises when using a search field that triggers a GET request to a service as the user types in the field. This functionality works smoothly unless the serv ...

Angular2 had a delay in processing the 'mouse wheel' input event for x milliseconds because the main thread was occupied

Currently, I am working with Angular2 (r.2.0.0) along with typescript (v.1.8.10). I have encountered an issue where Chrome does not respond while scrolling and displays a warning message stating: "Handling of 'mouse wheel' input event was delayed ...

Leveraging NFC in Ionic 2

I've been attempting to create a function that triggers a phone vibration whenever an NFC card is detected. I'm utilizing Ionic 2 and this plugin: https://github.com/chariotsolutions/phonegap-nfc This is the approach I tried. In the .ts file : ...

Angular Navbar-Toogle Not Functioning with Bootstrap 5

I encountered an error on my console related to Popper.js. Specifically, I am receiving the following error message: "scripts.js:7 Uncaught SyntaxError: Unexpected token 'export'." Due to this error, I suspect that my toggle button is not functio ...

Setting a global property within the complete method of an ngrx Angular subscriber is a helpful technique to ensure that

Currently, I have a global property called loadingIndicatorsearchVisible = false;. In addition, there is a method containing an observable, where I manipulate the loadingIndicatorsearchVisible to display or hide a loading panel. search(){ this.loadingI ...

Tips for keeping a specific key value pair as the final entry in a Typescript Object

My goal is to construct a Typescript Object that has a specific element with the key 'NONE' always positioned at the end. This arrangement is crucial for displaying the object in my HTML page with this value appearing last. I am seeking an implem ...

Struggling to increment the badge counter in a React Typescript project

I'm a bit unsure about where to apply the count in my Badge Component. The displayValue should include the count, but I'm struggling with how to implement it. UPDATE: The counter is now in place, but when I decrease the count and it reaches 0, t ...