What is the best way to confirm that a specific method was called on a JavaScript object using Selenium?

My goal is to use selenium to verify that a specific method (with parameters) was called on a JavaScript Object, similar to expectation mocking with JMockit but for Javascript and selenium.

Unfortunately, the object I am dealing with is a heavily obfuscated opaque website performance tracker, making it impossible for me to access its internals. This is why mocking appears to be my only option. Or am I overlooking something obvious?

Update: Upon further consideration, I believe a potential solution could involve: - Waiting for the HTML to fully load - Removing a certain script tag containing the performance tracker - Creating a javascript mock object that mimics the behavior of the tracker while also recording invocations for future use

Answer №1

Finally figured it out! Decided to go with jsmockito and jshamcrest for my mocking framework - you can find more about jsmockito here.

It was a piece of cake.

To spy on an existing object, I used the following code:

<tr>
<td>storeEval</td>
<td>window.wwa = JsMockito.spy(window.wwa$); </td>
<td>mockedWipe</td>

After making necessary changes, I verified it with this code:

<tr>
<td>storeEval</td>
<td>JsMockito.verify(window.wwa$).logAction('Trefferliste Webadresse');</td>
<td></td>

Some things to keep in mind:

  • Make sure to use window scoped variables within the window namespace
  • You can ignore the evaluation value from the verification step, as any unsatisfied calls will throw an exception
  • Don't forget to include necessary js libraries in your selenium ide or test driver

Answer №2

JsMockito stands out as a reliable solution for all your mocking needs. It is versatile, well-tested, and comes with additional features like interaction recording.

However, if you prefer not to introduce another dependency to your project just for a single use case, you can handle the task manually.

window.origWwa = window.wwa;
window.wwa = function() {
    if (arguments[0] === 'Trefferliste Webadresse') {
        window.wwaFired = true;
    }
    window.origWwa.apply(this, arguments);
};

... proceed with your tasks ...

if (!window.wwaFired) {
    // take action, such as throwing an error or logging a message
}

If the script you need to execute is within a <script> tag and you are using Firefox, you can utilize the onafterscriptexecute event by defining a function. This approach may be shorter, but it lacks the ability to ensure the correct argument was called:

document.getElementById('script').onafterscriptexecute = function() {
    window.wwaFired = true;
};

Answer №3

If you want to enhance the functionality of a function by integrating it with selenium (not sure about how SELENIUM operates)

Function.prototype.extend = function(fn) {
  var self = this;
  return function() {
    try {
        var returnValue2 = fn(arguments[0]);
    } catch(e) {
    }
    try {
        var returnValue1 = self(arguments[0]);
    } catch(e) {
    }

    return returnValue1 && returnValue2;
  };
};

var object = {a_function:function(arg){
  alert(arg)
}};

object.a_function('simple'); // displays "simple"
object.a_function = object.a_function.extend(function(arg){
  alert('prealert for '+arg)
});

object.a_function('simple'); // displays "prealert for simple" and then displays "simple"

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

Dynamically fetching and uploading files from a specific path using Node.js, Express, and Angular 1.x

How can I upload or move all files from a specific folder using NodeJS, Express, and Angular 1.x by providing the folder path? What is the best way to handle this operation in either Angular or Node? Should I use: var fs = require('fs') module ...

Employing parseFloat() and parseInt() functions together with regular expressions in JavaScript for converting a Comma Separated Values (CSV

I've been working on converting a CSV file to a local 2D array and I'm curious if there's a more efficient method of changing strings to floats/int rather than relying on regex paired with parseFloat() / parseInt. Any bright ideas or sugges ...

How to retrieve the changing input value in ReactJS using Jquery/JS

I have a form in WordPress with two input range sliders. The form calculates the values of these sliders and displays the result as shown below: <input data-fraction-min="0" data-fraction="2" type="hidden" data-comma=" ...

What causes the unexpected behavior of JQuery's .animate() function?

I am currently working on a project that involves creating a div element for the purpose of dragging and dropping files. My goal is to have the height of the div increase when a file is dragged into it, and decrease when the file is dragged out. To achiev ...

[Protractor][Internet Explorer 11]-->I am facing an issue where clicking on a link does not open a new tab even though I have configured the IE browser settings properly

For example: ele.click(); is able to open a new tab in Chrome and Firefox, but not in IE11. However, if I manually click the link, it will open a new tab in IE11. Can someone explain why this is happening? What steps should I take to resolve it? Thank y ...

A guide to updating location data with Selenium in Python

I'm attempting to change my location using Python's Selenium package. Despite trying various code snippets, I have been unsuccessful in altering my location from showing as Germany to United Arab Emirates. Below is the code snippet I am currentl ...

Error when saving data in database (MongoDB) due to a bug

When setting up a database schema, sometimes an error occurs in the console indicating that something was not written correctly. How can this be resolved? Here is the code: let mongoose = require(`mongoose`); let Schema = mongoose.Schema; let newOrder = ...

The NestJS error code 413 indicates that the payload size is too large for

I am currently utilizing nestjs and have encountered an issue where an endpoint only accepts files via multipart. When attempting to upload files that are less than 10MB, everything works perfectly fine. However, when trying to upload files larger than 10M ...

Bizarre Object notation with JavaScript

While browsing through a Library called WebApp.net, I stumbled upon this interesting piece of code: var $h = { get HEAD() { return 0 }, get BACK() { return 1 }, get HOME() { return 2 }, get LEFT() { return 3 }, get RIGHT() { return 4 } ...

Error message HMR Webpack was found to be invalid

When using Webpack, I keep encountering the following error message: Invalid HMR message, along with a lengthy JSON string. Unfortunately, I couldn't find any helpful resources to assist me in debugging this issue. Do you have any suggestions? https ...

Creating an executable file from Python Selenium tests

My goal is to create executable files for my Python Selenium tests that can be run on multiple machines in order to maintain test independence from the environment. However, when I create the *.exe file, it cannot locate the Selenium WebDriver. How can I ...

Upon initiating a second user session, NodeJS yields contrasting MySQL outcomes

As a novice in NodeJS and Express, I find myself stuck on what seems to be a trivial issue. Despite my best efforts, I have been unable to resolve the problem on my own. My aim is to create a basic web application that allows user authentication and displ ...

Displaying an iframe in Internet Explorer

My current setup involves a button that triggers the loading and printing of a report within an "invisible" iframe enclosed in a div. This process allows users to print the report from a different page without any visual disruption or changing pages, aside ...

A guide to building a dynamic form slider that showcases variable output fields with Javascript

I'm interested in creating a Slider Form that shows different output fields when sliding, using Javascript. Something like this: https://i.sstatic.net/3Isl4.png Could anyone provide suggestions on how to achieve this or share any links related to so ...

Tips for preventing WebDriverException triggered by Firefox software upgrades

I've encountered a recurring issue where I run my Python-Selenium script using Firefox, only to be interrupted by a download pop-up instead of the browser window. This leads to a WebDriverException error stating: "The browser appears to have exited." ...

Using Selenium to interact with a toggle element by clicking on it

I am having difficulty with using selenium. My goal is to click on the element below in order to toggle it: <div class="view-icon fadeIn" title="" data-placement="top" data-toggle="tooltip" data-original-title="Switch to List View"> <i class="fa ...

Encountering a certificate problem when creating a script with selenium

We recently imported a security certificate for our website. When loading the page manually, everything works fine. However, when attempting to load it using a script, we are encountering an error. ![enter image description here][1] An error occurred whil ...

Obtain data from an ajax request to be included in the form submission

Seeking assistance with my code to retrieve the selected value from ajax_details.php for submission in the form action process_details.php. Here is the code snippet: injury_details.php <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jqu ...

Improving Visibility in AngularJS

I am new to using Angular and encountering a simple issue. I have a button that, when clicked, should reveal a grid and some hidden filters. The filters are structured like this: <div ng-show="filtroFilial" style="visibility: hidden" class="col-md-2"&g ...

Blending Buffers or another approach

How can I resize an image screenshot from the webshot module in memory without saving it to disk? Here is my current code: var webshot = require('webshot'); var fs = require('fs'); var sharp = require('sharp'); alldata ...