Testing Angular 2 components with material icons and images

Recently, I finished creating a unique component that showcases an image, material icons, and a custom directive known as ticker. This directive allows for scrolling text if it exceeds the width of the element.

https://i.stack.imgur.com/GpDSr.png

My next challenge involved delving into unit testing using karma within angular cli/webpack. While most of the setup is clear to me, I've hit a roadblock in configuring images, material icons, and getting the HostListener directive to function properly.

This is what I have managed to piece together until now:

https://i.stack.imgur.com/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';

/* Custom Components & Services */
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;

  /* Stubbed Service Data */
  let foodDataServiceStub = [{
    name: 'test food name ..................', // Test long name triggering 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 correctness
      providers: [
        { provide: FoodDataService, useValue: foodDataServiceStub },
        { provide: WorkingDataService, useValue: workingDataServiceStub } ,
        MdIconRegistry // Uncertain about correctness
      ],
      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 have the correct food name', () => {
    expect(el.textContent).toContain('test food name ..................');
  });
});

Image: In the same directory as the spec.ts file, there is a png named 'no_image.png'. The framework identifies the image without any 404 errors, yet it fails to render.

Ticker Directive: The span associated with the ticker seems correctly set up, but the HostListener isn't responding to mouseover events as expected. I attempted importing HostListener into TestBed, which resulted in an error.

Material Icons: Although the ligatures of the material icons are visible, they do not render on the screen. Research suggested importing Http, but this led to another error.

I would greatly appreciate assistance in implementing these features, along with guidance on troubleshooting similar issues in the future (my attempts at finding solutions via search engines proved fruitless).

Answer №1

The component does not require high-level logic, making it difficult to write extensive unit tests. Instead, integration testing is recommended for testing the value, color, and size of the component.

INTEGRATION TESTING involves combining individual units and testing them as a group to identify faults in their interaction. Test drivers and test stubs play important roles in Integration Testing.

Learn more about Integration Testing

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

Creating fake classes and mocking class methods in Python unit tests

Using python's unittest.mock for testing in a Django application, I am trying to verify that a class is called and a method on its instance is also called. Consider the following simplified example code: # Inside project/app.py def do_something(): ...

Facing challenges with parsing JSON files in an Angular 2+ application

Utilizing the Angular CLI, I have configured this project with the standard folder layout. My goal is to practice reading a JSON file from src/app/assets/items.json and then using it to display these items in the HTML. items.json: { "results": [ ...

Error: Missing npm install -g @angular/cli@latest package in devDependencies section

ng build is causing an issue that The error reads: Unable to Find npm install -g @angular/cli@latest in devDependencies. When I attempt to start the application using npm start, it works fine. However, while trying to build a file, I encounter this er ...

Transforming Typescript Strings into ##,## Format

As I've been using a method to convert strings into ##,## format, I can't help but wonder if there's an easier way to achieve the same result. Any suggestions? return new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, max ...

Issue occurred when trying to load controllers during the migration process from AngularJS1 to Angular6

Currently, I am in the process of upgrading AngularJS1 components to Angular6. My strategy involves creating wrappers for all existing AngularJS1 components by extending "UpgradeComponent" and storing them under the folder "directive-wrappers". However, wh ...

Unable to simulate axios instance in a Typescript environment

After reading through this particular article, I decided to attempt writing a unit test while simulating Axios (with Typescript). Incorporating an Axios instance to define the baseUrl. // src/infrastructure/axios-firebase.ts import axios from 'axios ...

Discover how to capture and process POST form data in Angular originated from external sources

I am currently building a website that utilizes Java for the backend and Angular for the frontend. I have encountered a scenario where external websites may transmit data to my site via POST form submissions. For example, ▼ General    & ...

issues arise when deploying the Angular application on GitHub pages

Encountered an error while attempting to deploy my Angular application on GitHub pages using angular-cli-ghpages The bash commands I used when pushing the website to GitHub were as follows: ng build --prod --base-href "https://dinith72.github.io/aiese ...

Angular 4 and the process of HTML encoding

Looking for assistance with html encoding in angular 4. I have product records stored in a database, with the fullDescription field in this particular format: &lt;div align="justify"&gt;&lt;span&gt; When using <div *ngIf="product" [inn ...

The Material UI Datagrid is failing to display any data

I'm currently facing a challenge that has left me scratching my head. I've implemented Material UI Datagrids, but for some reason, I can't get it to populate with data, and the reason eludes me. Even though the Component profiler shows that ...

Testing the $resource PUT request in AngularJS

Within my AngularJS 1.2.10 application, everything runs smoothly except for the unit tests. Whenever I attempt to update a record (HTTP PUT) using $httpBackend, the callbacks fail to trigger, leading to test failures. The specific controller method under ...

Is it possible that overwriting my observable variable will terminate existing subscribers?

I am looking for a way to cache an http call and also trigger the cache refresh. My UserService is structured like this: @Injectable() export class UserService { private currentUser$: Observable<User>; constructor(private http: HttpClient) { } ...

Wait for Protractor until the page has completely finished loading

After navigating to https://docs.angularjs.org/tutorial, I attempted to click on '0 - Bootstrapping' under Tutorial but Protractor did not wait for the page to fully load, resulting in an Error. Error: Failed to execute 'click' on &a ...

Having trouble with Angular 5's Post function?

Having some trouble with my Angular 5 application and API calls. For some reason, when I add headers to the request, the browser is not recognizing them properly and showing 'OPTION' instead of the actual headers. This is resulting in a 403 respo ...

Maintain the nullability of object fields when casting

I have been working on a type called DateToNumber that converts all the Date properties of an object to number. Here is what I have come up with so far: type LiteralDateToNumber<T> = T extends Date ? number : T extends Date | null ? number | nu ...

The art of expanding Angular's HTTP client functionality

I understand that the following code is not valid in Angular, but I am using it for visual demonstration purposes. My goal is to enhance the Angular HTTP client by adding custom headers. I envision creating a class like this, where I extend the Angular h ...

Developing in Angular 2: Enhancing JSON data before passing it to the template

After receiving data from a JSON source, I have the following: { "name": "Leonardo", "weapon": "sword" }, { "name": "Donatello", "weapon": "stick" }, { "name": "Michelangelo", "weapon": "nunchucks" }, { "name": "Raphael", " ...

Utilizing TypeScript to Retrieve the Parameter Types of a Method within a Composition Class

Greetings to the TS community! Let's delve into a fascinating problem. Envision having a composition interface structured like this: type IWorker = { serviceTask: IServiceTask, serviceSomethingElse: IServiceColorPicker } type IServiceTask = { ...

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 ...

Updating a property in a JavaScript object using Angular

Working with Angular, I have a dataset: export class AppComponent { data = [ { "area1": { "format": "changethis" } ] I am looking to develop a function that can alter the value of a specific key. For e ...