Encountering a Lint error stating "Expected 2 arguments, but received 1" during the testing of the window.scrollBy() function in Jasmine following an Angular

During the upgrade to Angular 11, several other packages, such as jasmine-core, were also upgraded. This caused lint issues when running the 'npm run test' command due to stricter type definitions.

One specific issue involves the window.scrollBy() method. According to the type definition file (lib.dom.ts), it can have two overloaded implementations as shown below:

scrollBy(options?: ScrollToOptions): void;
scrollBy(x: number, y: number): void;

However, when writing a unit test case, a lint error is encountered:

it('should scroll down by 10 units', fakeAsync(() => {
    service.scrollDown(10);
    expect(window.scrollBy).toHaveBeenCalledWith({
      top: 10,
      left: 0,
      behavior: 'smooth',
    });
  }));

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

It appears that only the second overloaded implementation is being considered, ignoring the first one where only the "options" parameter can be passed. Despite this, the test case passes successfully.

I have provided a minimal reproduction example on the following Github link. Any additional information required is appreciated. Any assistance or guidance would be welcomed.

https://github.com/HimanshuGoel/scrollByIssue

Answer №1

In the scenario you highlighted, the scrollBy() function is overloaded, alongside other scroll functions such as scrollTo(). A known issue arises with the toHaveBeenCalledWith() function when dealing with overloaded functions. More information on this can be found here: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/42455

To satisfy the compiler, you can directly examine the arguments of the initial call using any:

it('should scroll down by 10 units', fakeAsync(() => {
    const spy = spyOn(window, 'scrollBy');
    service.scrollDown(10);
    expect(spy.calls.argsFor(0)).toEqual([{
      top: 10,
      left: 0,
      behavior: 'smooth',
    } as any]);
  }));

However, there may be situations where this approach is not effective, especially when there are multiple calls to the spy function and it is unclear which one is correct. I encountered such a scenario recently, prompting me to use // @ts-ignore in my code for the first time in my 5 years of using TypeScript.

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

Can someone explain how to define "a type of object that must not be empty" in typescript?

I'm working with a function that can operate on any type T, but with the constraint that if T is an object, it cannot potentially be empty. Here's what I've tried: declare function myFunction<T>(param: T extends Record<string, neve ...

Error: The property you are trying to set is undefined and cannot

When I attempt to set a property 'error' that is undefined, I receive a TypeError. The problematic line of code looks like this: this.error = error.code; This issue arises in an Angular Reactive Form while making a call to a web service. Below i ...

Leverage predefined JavaScript functions within an Angular template

I have been attempting to execute an eval function within my angular template in the following manner: <div *ngFor="..."> <div *ngIf="eval('...')"></div> </div> You understand what I'm trying to ...

Tips for Receiving Error Messages with Patterns in Angular 2

After several attempts, I am unable to get this code to function correctly. <div> <span *ngIf="!usernameRef.errors?.required">Amount</span> <span *ngIf="!usernameRef.errors?.required">Cover amount is necessary.</span& ...

What is the best way to swap out one component for another in a design?

I am working with a component that has the selector 'app-view', and I need to replace a specific part of the template: <div> content </div> The part that needs to be replaced will be substituted with another component: selector: &a ...

What are the appropriate scenarios for extending and utilizing an abstract class in Angular?

@Component({ selector: 'my-component', template: `<ng-content></ng-content>`, providers: [ { provide: AbstractClass, useExisting: forwardRef(() => TargetComponent) } ] }) export class TargetComponent extends AbstractCla ...

TypeScript class that utilizes internal functions to implement another class

In my journey of exploration, I decided to try implementing a class within another class in TypeScript. Here is the code snippet I came up with and tested on the Playground link: class A { private f() { console.log("f"); } public g() { console.lo ...

Exploring the world of logging in Nestjs to capture response data objects

I'm eager to implement logging for incoming requests and outgoing responses in NestJs. I gathered insights from various sources including a post on StackOverflow and a document on NestJs Aspect Interception. I'd love to achieve this without rely ...

Discover the most effective method for identifying duplicate items within an array

I'm currently working with angular4 and facing a challenge of displaying a list containing only unique values. Whenever I access an API, it returns an array from which I have to filter out repeated data. The API will be accessed periodically, and the ...

The NestJS server encounters an unhandled exception leading to a server

As a newcomer to Nest.js and in the process of building a REST API server with typeorm, I have encountered an issue related to async functions. If I forget to include the await keyword while using an async function, it may result in an exception like &apos ...

The file parameter in the upload is consistently undefined in tsoa-swagger

Having trouble with Tsoa nodejs File upload Followed the tsoa documentation for writing the method, but the output variable is consistently undefined This is my current method https://i.sstatic.net/YrNc0.png @Post('/uploadNewExporterTemplate&apos ...

Tips for importing bootstrap scss efficiently in an angular project to prevent style duplication

Is there a way to optimize an Angular project for utilizing Bootstrap's mixins and variables without constantly importing the styles in every component? Currently, the project I'm working on imports the variables.scss file multiple times due to u ...

How can I retrieve the height of a dynamically generated div in Angular and pass it to a sibling component?

My setup consists of a single parent component and 2 child components structured as follows: Parent-component.html <child-component-1 [id]="id"></child-component-1> <child-component-2></child-component-2> The child-compo ...

What steps are necessary to integrate barrel file imports with my Angular 2 application?

Following the Angular 2 style guideline 04-10 Create and Import Barrels can be challenging, as it may lead to unexpected file loading issues. When running my app, I noticed that Angular attempts to load a non-existent file named "my-component-name-here.js" ...

Combining objects in Angular forms: adding one object to another

I'm facing an issue with linking an angular object to another. Currently, I have a Company object with a property called 'accounts', which is an array of FiAccounts. export class Company { id : number; name : String; country : String ...

Collaborative input within configuration elements of components (syntax for configuring components)

My component is quite complex with numerous **@Input()**s and for better organization, I wish to group the inputs similar to how DexExtreme's grids do. The way DevExtreme grids handle their Inputs is by separating them like this: <dx-data-grid ...

How can I extract a specific data value from a JSON file in Ionic 2?

Here is the JSON data: [ { "id": 1, "label": "saw", "total": "100" }, { "id": 2, "label": "saw1", "total": "300" }, { "id": 3, "label": "saw2", "total": "400" } ] Below is my Typescript code snippet: this. ...

"Receiving HTML response from an HTTP GET request in Angular 2

Attempting to transmit test data from my node.js server to the front end. router.get('/abc', (req, res) => { return res.json({ test: "success!" }); }); In my service component: private url = "http://localhost:4200/auth/abc"; getTitl ...

What is the best way to display the output of a Set-typed function using a class key in my code?

I'm currently working on developing a function that can return a Set containing the keys of a class. However, I am struggling to determine the correct definition for this function. class Bot { public no01: number; public no02: number; construct ...

Angular input field displaying X

Hey everyone, I'm currently working with Angular and typescript. I have a requirement to hide the first 8 characters that the user enters and only show the remaining 4 characters. Update: I have included a link to the Stackblitz demo Stackblitz <i ...