Exploring ways to effectively test material2 icons using unit tests

This particular component utilizes material icons.

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

Currently, I am delving into learning unit testing with karma (via angular cli/webpack) and have most of the configuration set up to create the component. However, I am encountering difficulties in configuring for material icons.

Here is my progress so far:

https://i.sstatic.net/9lC01.png

/* configuration */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { TickerDirective } from '../../directives/ticker.directive';
import { MdIconModule, MaterialModule } from '@angular/material';
import { MdIconRegistry } from '@angular/material/icon';

/* my content */
import { FoodListComponent } from './food-list.component';
import { FoodDataService } from '../../services/food-items/food-data.service';
import { FoodItem } from '../../diet/food-item';
import { WorkingData } from '../../services/working-data/working-data';
import { WorkingDataService } from '../../services/working-data/working-data.service';

describe('FoodListComponent', () => {
  let component:          FoodListComponent;
  let fixture:            ComponentFixture<FoodListComponent>;
  let foodDataService:    FoodItem[];
  let workingDataService: WorkingData;
  let de:                 DebugElement[];
  let el:                 HTMLElement;

  /* Stub Services */
  let foodDataServiceStub = [{
    name: 'test food name ..................', // purposefully long to test the ticker directive
    img: './no_image.png',
    description: 'test food description'
  }];

  let workingDataServiceStub = {
    today: new Date(),
    selectedDate: new Date(2016, 2, 5),
    targetDate: new Date(2016, 2, 7),
    data: {exercise: 'Squat'}
  };

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [ FoodListComponent, TickerDirective ],
      imports: [ MaterialModule.forRoot(), MdIconModule], // unsure about this
      providers: [
        { provide: FoodDataService, useValue: foodDataServiceStub },
        { provide: WorkingDataService, useValue: workingDataServiceStub } ,
        MdIconRegistry // uncertain if this is correct
      ],
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(FoodListComponent);
    component = fixture.componentInstance;

    /* Inject services */
    foodDataService = TestBed.get(FoodDataService);
    workingDataService = TestBed.get(WorkingDataService);

    /* Assign Services */
    component.workingData = workingDataService;
    component.foods = foodDataService;

    fixture.detectChanges();
    de = fixture.debugElement.queryAll(By.css('span'));
    el = de[0].nativeElement;
    // console.log(el);
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
  it('should display the accurate food name', () => {
    expect(el.textContent).toContain('test food name ..................');
  });
});

Material Icons Issue Although the ligatures of the material icons can be seen, they are not appearing correctly. I came across a suggestion to import Http but that resulted in an error.

Answer №1

While facing a challenge with unit testing my components, I couldn't find a solution online so I took matters into my own hands.

For those using Angular-CLI: To solve the issue, simply include the code snippet below at the end of your test.ts file.

const materialIcons = document.createElement('link');
materialIcons.href = 'https://fonts.googleapis.com/icon?family=Material+Icons';
materialIcons.rel = 'stylesheet';
document.head.appendChild(materialIcons);

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

Unusual function call patterns observed in generic classes

After compiling the code below, it runs without any issues interface A { x: string; } interface B { x: string; } type C<D extends A> = D | B; declare function funcA<D extends A, E extends C<D> = C<D>>(): E | E[] | undefined; d ...

Having trouble generating a mock constructor for the user model

While attempting to simulate my user model in order to test my service, the nest console is throwing a TypeError. I am unsure of how to properly 'emulate' the constructor of the user model. user.service.spec.ts import { Test, TestingModule } fro ...

Instructions for altering the text attribute of sweet alerts in an Angular project

Here is a function with a parameter value that determines which custom text to display. Check out the code snippet below. buttonClicked(value) { console.log(value); swal({ title: 'Are you sure?', text: 'ssss', ...

"Utilizing FormData in an IONIC 5 project with

While creating a user profile, I am encountering an issue where the FormData being generated for sending is empty despite all other fields having values. Below is the code snippet from cadastro.ts: import { Component, OnInit } from '@angular/core&ap ...

Is there a way to retrieve the request URL within the validate function of the http strategy?

Is it possible to access the context object present in guards within the validate method of my bearer strategy, by passing it as an argument along with the token? bearer-auth.guard.ts: @Injectable() export class BearerAuthGuard extends AuthGuard('be ...

Getting started with Angular 2 and initializing component variables

Hey there, I'm new to angular2 and currently facing a challenge. Here's the Service section: getReports() { return this.http.get(GlobalVariable.BASE_API_URL + 'report/l', {headers: this.headers}).map(res => res.json()) ...

Tips for properly defining path names in loadChildren for lazy loading in Angular 2 NgModules

When setting correct path names for loadChildren in the app-routing.module file within an Angular 2 NgModule, I encountered some issues. Despite following the NgModule concept outlined on the Angular main website, I still couldn't find clear informati ...

Losing scope of "this" when accessing an Angular2 app through the window

My Angular2 app has exposed certain methods to code running outside of ng2. However, the issue arises when calling these methods outside of ng2 as the context of this is different compared to when called inside. Take a look at this link to see what exactl ...

What is the method to update reference models in mongodb by generating documents within a different model?

In my API, I have three models: Patient, Doctor, and Reviews. The Reviews model is referenced in the Doctor model, with the intention that a patient can post a review for a specific doctor using Review.create(). However, even after the review document is c ...

Unexpected behavior: ng2-dragula modelDrop event leading to undefined array

Struggling to figure out the issue with this code. As shown in this GIF, when dragging a div from one container to another, the object disappears and the array becomes undefined. https://i.stack.imgur.com/TELyc.gif Here is the code snippet: Main View.ht ...

Navigating API data conversion on the frontend using Object-Oriented Programming

Currently, I am facing a challenge while developing the frontend of a web application using TypeScript. The dilemma revolves around efficiently converting a data object from an API response into a format suitable for the application. Let's consider r ...

Removing API request in React.js

My approach: deleteSample = () => { this.sampleService .deleteCall(this.props.id) .then((response) => { window.location.reload(false); }) .catch((error) => { console.log ...

Determining the best application of guards vs middlewares in NestJs

In my pursuit to develop a NestJs application, I aim to implement a middleware that validates the token in the request object and an authentication guard that verifies the user within the token payload. Separating these components allows for a more organi ...

Comparing Node.JS using Typescript versus Javascript to Ruby On Rails

My question can be simplified as follows: 1. Does Ruby perform as well as Node with MongoDB? 2. Should I use Typescript or JavaScript with Node? I come from a .NET background (ASP.NET MVC) and am now venturing into creating an Angular project with a Mongo ...

Is there a way to adjust the dimensions of my Angular npm slider?

This snippet shows the Angular code I came across this npm slider on npm.js Struggling to adjust the margin of the images as they are sticking, also unsure about modifying the size and other elements using https://www.npmjs.com/package/ng-image-slider. A ...

Deploy an Angular 2 application on Firebase using Travis CI

I am attempting to deploy my Angular 2 application on Firebase using Travis CI, but it seems that the dist folder generated by ng build --prod cannot be located. Here is my .travis.yml # tavis.yml language: node_js node_js: - "7" branches: only: ...

What is the best way to bring a string into my .tsx file using a relative reference from a module?

I am currently developing an online course on creating a website using StencilJS, NodeJS, and the IonicFramwork. As a newcomer in this field, I have encountered a challenging issue: In my project, the API "https://swapi.dev/api" is imported as a ...

"Can anyone provide guidance on how to customize form fields in Angular Material 16, such as removing borders, changing colors, and other

After upgrading my angular material to version 16, all the UI elements I had in place became distorted due to the introduction of mdc. The CSS code I was using before to customize elements like this: ::ng-deep .mat-form-field-appearance-outline .mat-form- ...

How to specify the return type of a promise from an observer in Angular 6

Typically, I prefer using observables. However, in order to avoid 'callback hell' in this particular scenario, I decided to use toPromise(). Unfortunately, I encountered a lint error message when trying to define the return type: The 'Obj ...

Unable to display component on the DOM - Angular

My component seems to be causing interference with other components in my app. When I try to render this component in app-root, my component with Google Maps stops rendering properly. Below is the code snippet for the troublesome component: import { Compo ...