What is the best way to spy on a property being called within a function?

I am facing an issue where the 'offsetWidth' value is undefined and I need to spyOn it. The function getCurrentPage retrieves an element based on the id currentpage.

Although spying on getCurrentPage works, I have been unable to declare the offsetWidth successfully.

Functions:

getCurrentPage() {
    return this.$document[0].getElementById('currentPage');
}

calculateStep() {
    this.stepWidth = this.getCurrentPage().offsetWidth / (this.totalSteps - 1);
    return this.stepWidth;
}

Unit test:

let stepWidth = new StepController();
stepWidth.totalSteps = 5;

const dummyCurrentPage = '<div id="currentPage" style="width: 20%;"></div>';

spyOn(stepWidth, 'getCurrentPage').and.returnValue(dummyCurrentPage);

const expectedResult = '200 / 4';

const result = stepWidth.calculateStep();

expect(result).toBe(expectedResult);
});

I am trying to figure out how to spyOn the offsetWidth of this.getCurrentPage().offsetWidth?

Answer №1

Successfully located the solution by converting dummyCurrentPage to an angular.element and setting the offsetWidth to match.

const newElement = angular.element('<div id="currentPage" style="width: 20%;"></div>');

dummyCurrentPage.offsetWidth = 50;

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

What could be the reason for the Nextjs fetch request returning undefined data?

Here is the code snippet for my GET request in the API section: export default async (req, res) => { const { query: { className }, method } = req; switch (method) { case "GET": try { const classDetail = await Class.findO ...

use ajax to dynamically append a dropdown menu

Currently working on creating a form that includes a dropdown menu populated with elements from a database. The challenge I'm facing is ensuring that once an element is selected from the dropdown, another one appears dynamically. My goal is to use AJA ...

Is an audio player/playlist necessary for showcasing a mix engineer's skills in their

As a newcomer to the world of web development with some background knowledge from school, I work as a mix engineer and have created a portfolio website. Previously, I utilized Soundcloud and Spotify's API to showcase my mixes/songs, but the external J ...

Issue encountered while deploying Next.js application on vercel using the replaceAll function

Encountering an error during deployment of a next.js app to Vercel, although local builds are functioning normally. The issue seems to be related to the [replaceAll][1] function The error message received is as follows: Error occurred prerendering page &q ...

Passing parameters from the Angular template to the controller and then onwards to the service

Currently, I have a code that utilizes Resources to generate and list items using APIRest. My goal is to effectively pass an Id from the template to the controller and subsequently to the service. Below is my code snippet: Template.html <div class="i ...

Enhancing the accessibility of Material UI Autocomplete through a Custom ListboxComponent

I have developed a custom ListboxComponent for the MUI Autocomplete component in MUI v4. How can I ensure that it meets the necessary accessibility requirements, such as navigating through options using the arrow keys? <Autocomplete ListboxComponent ...

Having issues with v-for in Vuejs? It seems to be looping multiple times

<div v-for="item in items" :key="item.id"> <div v-for="accordion in accordions" :key="accordion.title" class="line" :class="{ green: accordion.text === 'AllaboutVue', red: accordi ...

What is the best way to convert the data stored in an object to an array?

I have a function that is constantly checking for temperature data: {"a":"43", "b":"43", "c":"42", "d":"43", "e":"40", "f":"41", "g":"100", "h":"42.6"} My goal is to graph this data over time, but I'm struggling with how to structure it to fit the f ...

Guide on how to return a JSON result as a Dictionary instead of an Array using Express.js

I need to format my response as a dictionary with specific key-value pairs, like so: { "id": 5928101, "category": "animal welfare", "organizer": "Adam", "title": "Cat Cabaret& ...

Error: The method specified in $validator.methods[method] does not exist

Having trouble solving a problem, despite looking at examples and reading posts about the method. The error I'm encountering is: TypeError: $.validator.methods[method] is undefined Below that, it shows: result = $.validator.methods[method].call( t ...

NodeJS: Implement a method to delete a file or folder using a path without the file extension (Strategic approach)

I am facing a challenge in deleting a file or folder based on a path that does not include an extension. Consider the path below: /home/tom/windows The name windows could refer to either a folder named windows OR a file named windows.txt Given that the ...

What are the steps to ensure the effective functioning of my checkbox filter?

Currently, my product list is dynamically created using jQuery. I now need to implement filtering based on attributes such as color, size, and price. I found some code that filters the list items by their classes, which worked perfectly for someone else. ...

Having trouble locating the module recommendations on my Angular 1.6 app while using Browserify

My app is not able to find suggestions.module even though it loads am-suggestions-lib.js. I am using angular 1.6 and browserify, but I can't figure out what I'm doing wrong. Here are all the relevant files: View the tree here suggestion.module. ...

What is the correct way to display the date in a React application?

I am working on a project that involves integrating solidity contracts into a web portal. In one of the contracts, I have stored dates as uint values like this: 1539491531. However, when I display these dates on the web page, they appear different from wh ...

Running PHP scripts from JavaScript

Currently working on a PHP project that involves a dropdown select button in a webpage. The goal is to call a JavaScript function whenever the value of the dropdown changes, and then pass this selected value to retrieve additional details from a MySQL da ...

issue involving extension that interrupts downloads

Trying to develop a browser extension that can intercept downloads and automatically rename them. manifest.json: { "name": " Book Renamer", "description": "Automatically rename downloaded ebooks from gutenberg.or ...

Generate visual representations of data sorted by category using AngularJS components

I am facing an unusual issue with Highcharts and Angularjs 1.6 integration. I have implemented components to display graphs based on the chart type. Below is an example of the JSON data structure: "Widgets":[ { "Id":1, "description":"Tes ...

A guide on adding two fields together in AngularJS and displaying the output in a label

I am facing a unique issue on my webpage. Including two inputs and a label in the page, I want the label to display the sum of the values entered into these two inputs. My initial attempt was as follows: Sub-Total <input type="text" ng-model="Propert ...

implementing static routing and user authentication in an Express application

I'm having trouble implementing the following: All requests should serve files from the /public folder. (e.g. -> /public/docu/index.html) If the user is not authorized, they should be redirected to the "oauth/login" route. Here is what I'v ...

Implementing a function to load HTML pages upon clicking a button with JavaScript

I need help creating a button that loads an HTML page using JavaScript, without redirecting to the page. However, the current code I have is not loading the HTML page as desired. Here is the code snippet in question: <!DOCTYPE html> <html> &l ...