Directive's timeout function fails to execute

My goal was to experiment with a simple AutoScrollDirective.

@Directive({
  selector: '[appAutoScroll]',
})
export class AutoScrollDirective implements AfterViewInit {
  constructor(private element: ElementRef<HTMLElement>) {}

  @Input()
  delay = 100;

  ngAfterViewInit(): void {
    setTimeout(
      () => this.element.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' }),
      this.delay
    );
  }
}

Upon closer inspection, I noticed that it utilizes a setTimeout. I pondered whether this could be handled more effectively with a fakeAsync approach.

@Component({
  template: `<div appAutoScroll></div>`,
})
class TestAutoScrollDirectiveComponent implements AfterViewInit {
  ngAfterViewInit(): void {}
}

describe('AutoScrollDirective', () => {
  let fixture: ComponentFixture<TestAutoScrollDirectiveComponent>;
  let component: TestAutoScrollDirectiveComponent;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AutoScrollDirective, TestAutoScrollDirectiveComponent],
      imports: [BrowserDynamicTestingModule],
    });

    fixture = TestBed.createComponent(TestAutoScrollDirectiveComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should call scrollIntoView of the element', fakeAsync(() => {
    const scrollIntoViewMock = jest.fn();
    HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;
    component.ngAfterViewInit();
    tick();
    expect(scrollIntoViewMock).toHaveBeenCalled();
  }));
});

However, I encountered a hurdle where the function within the setTimeout is never triggered. Despite my attempts at debugging, the issue persists as it appears to reach ngAfterViewInit and invoke setTimeout but no action is taken.

Edit:

In an effort to resolve this, I explored the solution provided in this post. While it serves as a temporary workaround, I am open to suggestions for a more optimal resolution.

Answer №1

Consider utilizing:

tick(101);

in place of

 tick();

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

Switch back emulation when moving away from page - using angular javascript

I have a unique scenario in my component.ts file on a specific page where I need to incorporate custom CSS for printing purposes: @Component({ selector: "dashboard", templateUrl: "./dashboard.component.html", styleUrls: ["./d ...

A step-by-step guide on customizing the background color of a Dialog in Angular Material (Version 16)

I've been attempting to modify the background color of my Angular Material Dialog by utilizing the panelClass property in the MatDialogConfig. Unfortunately, I'm encountering a partial success. I am aiming to set the background color as red (jus ...

The NgModel within the parent component is expected to mirror the state of the child component

My Angular 10 project includes a library with a wrapper component around a primeng-component. The primeng-component utilizes ngModel. I am trying to set the ngModel in the parent-component accessing the wrapper-component, and I want any changes made to the ...

What could be causing the appearance of "null" on the screen in an Angular 5 application?

I'm using a straightforward template to show the value of a string: <span class="fax_number">{{company.fax}}</span> However, when the value is empty, the screen displays "null" instead of an empty string. This seems to be happening in mu ...

How to Connect Select Dropdown to a Static Array Object in Angular 2

I have connected my Select DropDown to static data. FieldModel.ts export interface Field { id : number; title : string; } app.PeopleListService.ts import { Injectable } from '@angular/core'; import { Field } from "../model/fieldMo ...

Troubleshooting the lack of success in enhancing global scope within Typescript

Currently, I am working on a microservices application where I have two very similar services that use practically the same packages. To perform some testing, I decided to add a function to the global scope and modified it slightly to prevent any TypeScrip ...

Tips for modifying the JSON format within a Spring and Angular project

I am utilizing Spring for the backend and Angular for the frontend. Below is my REST code: @GetMapping(path = "/endpoint") public @ResponseBody Iterable<Relations> getGraphGivenEndpointId(@RequestParam(value = "id") int id) { return ...

Using AngularJS2, store the AJAX data in a class variable

I'm currently working on this code and I'm struggling to understand why the data retrieved through AJAX isn't being assigned to the class variable this.users. Snippet of Code getUsers() { this.http.get('/app/actions.php?method=us ...

What is the best way to eliminate the alert message "autoprefixer: Greetings, time traveler. We are now in the era of CSS without prefixes" in Angular 11?

I am currently working with Angular version 11 and I have encountered a warning message that states: Module Warning (from ./node_modules/postcss-loader/dist/cjs.js): Warning "autoprefixer: Greetings, time traveler. We are now in the era of prefix-le ...

Is there a tool in Node.js to set up a new project, similar to the scaffolding feature in Visual Studio for C# projects

Is there a way to efficiently create a node.js project with TypeScript and Express, and embed an SPA client using React and Redux templates written in TypeScript as well? Is there a scaffolding tool available to streamline this process, similar to the ea ...

The module 'react' is not found in the directory '/react/node_modules/react-redux/lib/components'

Issue: Module react not found at path /home/react/node_modules/react-redux/lib/components While utilizing cypress for unit testing components, the tests are encountering the error mentioned above despite 'react' being present in the dependencies ...

What is the accurate type of control parameter in Typescript?

Recently, I developed a TypeScript React component called FormInput to use in my form. This component integrates the MUI framework and react-hook-form. However, I encountered an issue while trying to set the correct type for the "control" parameter in my c ...

The object[] | object[] type does not have a call signature for the methods 'find()' and 'foreach()'

Here are two array variables with the following structure: export interface IShop { name: string, id: number, type: string, } export interface IHotel { name: string, id: number, rooms: number, } The TypeScript code is as shown below ...

Angular2 Animation for basic hover effect, no need for any state change

Can anyone assist me with ng2 animate? I am looking to create a simple hover effect based on the code snippet below: @Component({ selector: 'category', template : require('./category.component.html'), styleUrls: ['./ca ...

An Array of objects is considered NULL if it does not contain any values before being iterated through

Working with Files in TypeScript (Angular 8) has led me to Encode the files in Base64 using the code below: private async convertToBase64(evidences: Array<EvidenceToDisplay>): Promise<Array<EvidenceToDownload>> { const results: Arr ...

Can you explain the concepts of observables, observers, and subscriptions in Angular?

As I dive into Angular, I find myself tangled in the concepts of observables, observers, and subscriptions. Could you shed some light on these for me? ...

Stop/continue a stopwatch Observable

I'm trying to create a basic stopwatch using angular/rxjs6. I've managed to start the timer, but I'm struggling with pausing and resuming it. source: Observable<number>; subscribe: Subscription; start() { this.source = tim ...

Angular template containing a material table within a virtual scroll component

I am attempting to incorporate the content of ng-template into the cdk-virtual-scroll-viewport (using the library: ng-table-virtual-scroll), but I am encountering an error. <cdk-virtual-scroll-viewport tvsItemSize [footerEnabled]="true" ...

Unable to dynamically load a script located in the node_modules directory

This particular approach is my go-to method for loading scripts dynamically. import {Injectable} from "@angular/core"; import {ScriptStore} from "./script.store"; declare var document: any; @Injectable() export class ScriptService { private scripts: an ...

Customizing page layout for pages wrapped with higher-order components in TypeScript

Looking to add a layout to my page similar to the one in this link: layouts#per-page-layouts The difference is that my page is wrapped with a HOC, so I tried applying getLayout to the higher order component itself like this: PageWithAuth.getLayout Howev ...