Steps for generating a unit test for code that invokes scrollIntoView on an HTML element

I'm currently working on an Angular component where I have a method that involves scrolling through a list of elements known as "cards" based on certain criteria. Despite my efforts to write unit tests for this method using the Jasmine framework, I've been struggling to make it work. Any suggestions or advice would be greatly appreciated!

Here's the code snippet of the method in question:

 scrollToCard() {
    const scrollSlotToMatch = '10:00 - 11:00';

    // Querying the DOM to select specific schedule card view elements for scrolling into view
    const matches = Array.from(document.querySelectorAll('test-card'));

    // Iterating through the card elements to identify the desired one matching the target scroll time
    let selectedCard: HTMLElement | undefined;
    for (let i = 0; i < matches.length; i++) {
      const card = matches[i] as HTMLElement;
      const cardInnerText = card.innerText.split('\n');

      if (cardInnerText[0] === scrollSlotToMatch) {
        selectedCard = card;
        break;
      }
    }

    // Scroll the located card element into view if found
    if (selectedCard !== undefined) {
      selectedCard.scrollIntoView();
    }
  }

Answer №1

If you want to test your component, one way is to create spies for each element's scrollIntoView method by iterating over a list of test-card native elements. By collecting these spies into an array, you can then verify the correct spy was called based on its index, which corresponds to the element's position in the list.

For example, if your component template includes test-cards like this:

<test-card content="8:00 - 9:00"></test-card>
<test-card content="9:00 - 10:00"></test-card>
<test-card content="10:00 - 11:00"></test-card>
<test-card content="11:00 - 12:00"></test-card>

Your test could resemble something similar to this:

it('ensures the target element scrolls into view', () => {
  const targetText = '10:00 - 11:00';
  const expectedCardIndex = 2;

  const cardDebugEls = fixture.debugElement.queryAll(By.css('test-card'));
  const scrollSpies = cardDebugEls.map((cardDebugEl: DebugElement) => {
    return spyOn(cardDebugEl.nativeElement, 'scrollIntoView').and.stub();
  });

  component.scrollToCard(targetText);

  scrollSpies.forEach((spy: jasmine.Spy, index) => {
    const expectedCallCount = index === expectedCardIndex ? 1 : 0;
    expect(spy.calls.count()).toBe(expectedCallCount);
  });
});

You can view an example of this testing approach in action on StackBlitz.

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

When there is data present in tsconfig.json, Visual Studio Code does not display errors inline for TypeScript

After creating an empty .tsconfig file (consisting solely of "{ }"), Visual Studio Code immediately displays errors both inline and in the "problems" section. Interestingly, when I populate the tsconfig.json file with data, these errors disappear. Is there ...

What is the process for defining a type that retrieves all functions from a TypeScript class?

Imagine having a class called Foo class Foo { bar(){ // do something } baz() { // do something } } How can you define a type ExtractMethods that takes a class and returns an interface or type containing the class methods? For example: t ...

React slick slider not functioning properly with custom arrows

"I have encountered an issue while trying to implement multiple sliders in my component with custom arrows positioned below each carousel. Despite following the documentation meticulously, the arrows do not respond when clicked. What could possibly be ...

Turn off TypeScript's type validation during production builds

For my petite project, I am utilizing Next.js with TypeScript. A thought has been lingering in my mind lately: is there a way to turn off the types validity checks while executing npm run build? Since the type checking occurs during npm run dev, it seems ...

Exploring Hands-On Navigation in Angular 6

Is there a way to navigate to another component in Angular 6 based on the result of a function? Login(){ console.log(this.LoginModel); this.userService.LoginUser(this.LoginModel).subscribe( result =>{ if( ...

Using an external module in a Vue SFC: a beginner's guide

Recently delving into Vue, I'm working on constructing an app that incorporates Typescript and the vue-property-decorator. Venturing into using external modules within a Single File Component (SFC), my aim is to design a calendar component utilizing t ...

Unable to log out of OIDC-client due to an error: end session endpoint not found

Currently, I am in the process of setting up a code flow with Auth0 as my chosen identity provider. Successfully, the sign-in process functions well and I receive a valid token from Auth0. However, I am encountering an issue when attempting to sign out ...

Angular list not refreshing

As a newcomer to Angular, I am facing a basic issue where my list does not get updated when I add a new object to my array. Whenever I tap on a button to add a new object to the array-list, the list fails to update. Additionally, I am grouping my array-li ...

Issue with Angular 2 NgFor Pattern Error Message Display Absence

I am attempting to incorporate inputs with a regex requirement within an ngFor loop, but I am not receiving the expected error message when entering something that does not match the required pattern. Even when I input an incorrect pattern, "Test" remains ...

Encountering issues with the command npm install --save web-animations-js, the

Issue encountered while trying to run "npm install --save web-animations-js". It seems like the request to https://registry.npmjs.org/web-animations-js failed due to a mismatch in the Hostname/IP in the certificate. The error message indicates that the Hos ...

Is there a way to use WithStyles<typeof styles> within Material UI?

import { WithStyles, createStyles } from '@material-ui/core'; const styles = (theme: Theme) => createStyles({ root: { /* ... */ }, paper: { /* ... */ }, button: { /* ... */ }, }); interface Props extends WithStyles<typeof styles> ...

Showing JSON object in an Angular 2 template展示JSON对象在模

When I execute the following code: stanservice.categoryDetail(this.params.get('id')) .then((data) => { this.category = JSON.stringify(data.res.rows[0]); console.log(JSON.stringify(data.res.rows[0])); }) .catch((error) => { ...

Testing controls in AngularJS is an essential part of verifying the

Just diving into the world of Angular and wanting to write some basic unit tests for my controllers, here is what I have so far. app.js: 'use strict'; // Define the main module along with its dependencies angular.module('Prototype', ...

ngx extended-pdf-viewer Unable to Load viewer ftl in Live Environment

Incorporating ngx-extended-pdf-viewer into my Angular project has been a smooth experience while running the app locally. However, once I deploy the application to the server, a series of errors plague the viewer and degrade the overall performance of the ...

Encountering an issue with Angular 2.0.1 Router where it throws an EmptyError due to

I am struggling to set up Angular 2 routing properly. I am currently using Angular 2 with Webpack. While looking at the Angular 2 webpack starter, I noticed they had webpack handling their html and links generation, but I was hoping to avoid webpacking my ...

Synchronously updating the state in Angular using NgRx

Currently, I have implemented NgRx-Effects along with an action to fetch data from a service and update my initial state. The state property name, let's call it 'schoolData', is functioning smoothly. However, I now require to modify the sam ...

Encountered an error while attempting to install the 'ionic-native' package

Currently, I am navigating through this particular link to integrate local notifications into my Ionic 2 application. To kickstart the process, I executed the following two commands: Username@DESKTOP-BNKQVBC MINGW64 ~/Reminder-App (platform-specific) $ n ...

Angular sub-route is failing to activate

My current setup involves Angular routing along with the use of ngx-translate-router, and I've encountered an unusual issue with child routes. It's unclear whether this problem is connected to the translated router module I'm utilizing, but ...

Tips on ensuring that only one Angular Material expansion panel expands at a time

I have designed a mat expansion panel and I would like to ensure that only one panel can be expanded at a time. In other words, I want it so that when one record is expanded and I click on another record of the mat expansion, the previously expanded reco ...

Display or conceal elements in Angular based on multiple conditions

Looking to develop a functionality where an array of objects can be shown or hidden based on specific filters. The desired output should be as follows: HTML CODE: Filter: <div (click)="filter(1)"> F1 </div> <di ...