Testing Vue with Jest - Unable to test the window.scrollTo function

Is there a way to improve test coverage for a simple scroll to element function using getBoundingClientRect and window.scrollTo? Currently, the Jest tests only provide 100% branch coverage, with all other areas at 0.

Function that needs testing:

export default function scrollToEl(el) {
  let elRect = el.getBoundingClientRect();
  return window.scrollTo(
    elRect.left + document.documentElement.scrollLeft,
    elRect.top + document.documentElement.scrollTop
  );
}

Existing Jest test with incomplete coverage:

import * as scroll from "../scrollToEl";

describe("scrollToEl test", () => {
  let element;
  let ev = jest.fn();
  scroll.scrollToEl = jest.fn(() => {
    ev;
  });
  beforeEach(() => {
    element = document.createElement("div");
  });
  it("should be called", () => {
    ev(element)
    expect(ev).toHaveBeenCalled();
  });
});

Any suggestions on achieving full 100% coverage in all categories? All help is appreciated.

UPDATE - achieved 100% coverage in all areas: https://i.stack.imgur.com/SxDSg.png

Updated JavaScript function:

I made changes to the initial export default function statement by converting it to

export const scrollToEl = function (el)

export const scrollToEl = function (el) {
  // ...
};

Revised Test:

To attain complete coverage, I simplified the test setup. The focus was on including and validating window.scrollTo behavior while executing the function on a newly generated element (el).

import * as scroll from "../scrollToEl";

describe("scrollToEl test", () => {
  beforeEach(() => {
    window.scrollTo = jest.fn();
  });
  it("`window.scrollTo` should be called", () => {
    const el = document.createElement("span");
    scroll.scrollToEl(el);
    expect(window.scrollTo).toHaveBeenCalled();
  });
});

Answer №1

Let's address the matter at hand, which is how to handle Jest complaints about scrollTo. The solution lies in mocking it.

You can silence Jest's complaints by implementing a mock for window.scrollTo like this:
window.scrollTo = jest.fn();

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

Harness the power of $compile within the Angular link function while also retrieving and utilizing the arguments of the

I am currently developing a custom directive in angular.js 1.x Here is how I call the directive: <mydirective dirarg={{value-1}}></mydirective> My goal is to define the directive by including code to alter the DOM within the directive's ...

Adding jQuery and other libraries to Typescript for optimal functionality

After spending days researching and struggling, I am reaching out here for clarification on the process of importing a library in Typescript. I used to just add the script tag and everything would work fine. Now that I am working on building a MEAN-Stack ...

Angular filter is causing an error message saying "Unable to interpolate," but the filter is functioning as expected

I have implemented the filter below (which I found on StackOverflow) that works perfectly fine on one page. However, when using the same object, it throws an error as shown below: app.filter('dateFormat', function dateFormat($filter){ return f ...

Utilize JSON data to display markers on Leaflet maps

I am exploring the world of Leaflet and I have a question about loading markers from a database into a leaflet map using PHP. In my PHP code, I extract latitude and longitude data from the database based on the selected ward and encode it in JSON format. ...

Regular expression is used to limit input to integers only, specifically numbers between -130 and 30

Completed the regex for 0 to 50 ^(?:[1-9]|[1-4][0-9]|50)$ The current regex is functioning correctly. Next step is to create a regex that includes negative numbers, allowing for values between -130 and 30 without any decimal points. ...

Console is displaying a Next.js error related to the file path _next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json

I keep getting an error in the console on my Next.js website. GET https://example.com/_next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json net::ERR_ABORTED 404 I'm puzzled as to why this is happening. Could it be that I'm mishandling the router? ...

Occurrences repeating several times following the incorporation of fresh content into the DOM

I am facing an issue with my plugin. I have implemented an update method to handle new elements added to the DOM. Initially, everything works perfectly without any errors or issues. However, when a new element (div with class "box") is added to the DOM, th ...

The PropertyOverrideConfigurer encountered an issue while processing the key 'dataSource' - The key 'dataSource' is invalid, it was expecting 'beanName.property'

During the installation of Sailpoint on Oracle, the configuration properties are as follows: ##### Data Source Properties ##### dataSource.maxWaitMillis=10000 dataSource.maxTotal=50 dataSource.minIdle=5 #dataSource.minEvictableIdleTimeMillis=300000 #dataSo ...

Utilizing Regular Expressions in AngularJS to validate name, a 10-digit mobile number, and a 12-digit number through the ng-blur event and match

I am struggling to validate the three inputs mentioned above and having trouble using the right functions. Can someone please assist me with this? Here is the HTML code for the 3 inputs: <input id="name" ng-model="user.name" ng-blur="checkIfNameIsVali ...

Loop through JSON data using jQuery for parsing

Here is the code snippet I have included below, which is a part of a larger code base: <html> <head> <style> #results{margin-top:100px; width:600px; border:1px solid #000000; background-color:#CCCCCC; min-height:200px;} </style> & ...

Which one is better: JSON in PHP or JSON in Javascript?

In my current project, I am working on a website that utilizes a PHP function to retrieve JSON data and present it on the webpage. However, I have noticed that when the page loads, it freezes until the response is successfully fetched, creating a visual di ...

Just starting out with d3, any easy methods to learn?

As a developer with a few years of experience under my belt, I recently discovered d3 and was really impressed by its capabilities. However, it seems like d3 doesn't have the same level of popularity as jquery, making it harder to find comprehensive d ...

The anchor tag is not being used in the function call in an Angular application

Having trouble with calling the logout function inside the login controller. The setup involves a simple login and logout system using ui-router. After successfully logging in and navigating to another page, I encountered issues with calling the logout fu ...

Choose Your Price - Price Grids

I need to incorporate two sets of pricing columns into a website. The first set is for regular car cleaning prices, while the second set is for larger cars with slightly higher prices. My idea is to have two buttons at the top – one for regular cars and ...

What could be the reason why this function in jQuery is not functioning properly?

I am trying to duplicate the span element inside the `test` element using the .clone method. It seems like it works as expected. However, when I try to use .html in a `.click` function, it doesn't work. Can someone point out where I went wrong and sug ...

Failed to make a request to https://registry.npmjs.org/node-modules because of an error: error:0906D06C:PEM routines:PEM_read_bio:no start line

Encountering an issue while attempting to install a JS package. Despite conducting thorough research, I have not been able to resolve the error. Please help me identify where I am going wrong. npm ERR! request to https://registry.npmjs.org/node-modules ...

Is it possible for me to observe the submit button or function in vue?

I have a query regarding the Vue watcher function. Is it possible to watch a function? For instance: when I click the submit button, can the watcher listen to the submit button and handle the function? <b-table :fields="tableFields" :items=&qu ...

"Enhance user experience with Sweetalert 2's customizable sorting options for select inputs

Here is the code snippet that I am currently working with: this.getdata((params.....).then((data) => { var selectOptions = []; for (let i = 0; i < data.length; i++) { selectOptions[data[i].id_calc] = data[i].surname + " " + data[i ...

Tips on capturing JSON data for export and sending it to a specific URL

After implementing the recommended code changes, I still cannot see any updates on the specified WordPress page - . It appears that there may be a login information or other issue preventing me from viewing the changes. Here is the updated code: // New ...

Navigating JSON Data with ES6 Iteration

Issue Description There are two APIs I am working with. The first one, let's call it API #1, provides JSON data related to forum posts as shown below: [{ "userId": 1, "id": 10, "title": "Tt1", "body": "qBb2" }, { "userId": 2, ...