Sinon and Chai combination for testing multiple nested functions

I attempted to load multiple external JavaScript files using JavaScript. I had a separate code for the injection logic. When I loaded one JavaScript file, the test case worked fine. However, when I tried to load multiple JavaScript files, the test case FAILED.

Main.js

var externalJs = "abcd.js";
function loadJs() {
  window.$script(externalJs);
}
function init(domElement) {
  loadJs();
}

module.exports = {
  init: init
};

Test.js

/* global assert, sinon*/
describe('Test', function () {
  var factory = require('main.js');
  it('load the correct JavaScript library', function(){
    window.$script = sinon.spy();
    factory.init();
    sinon.assert.calledOnce(window.$script);

  });
});

The above code works fine. However, when I attempt to load multiple external files, the test case fails.

Main.js

var externalJs = ["abcd.js", "xyz.js"];

function loadJs() {
  window.$script(externalJs[0], function(){
    window.$script(externalJs[1], function(){
    });
  });
}

function init(domElement) {
  loadJs();
}

module.exports = {
  init: init
};

Test.js

/* global assert, sinon*/

describe('Test', function () {
  var factory = require('main.js');
  it('load the correct JavaScript library', function(){
    window.$script = sinon.spy();
    factory.init();
    sinon.assert.calledTwice(window.$script);
  });
});

Error Details:

expected $script to be called twice but was called once

Any ideas on how to resolve this issue?

Answer №1

The issue lies in the fact that the initial invocation of window.$script fails to execute the provided callback function, leading to a chain reaction where subsequent calls to window.$script also do not trigger the callback.

Instead of opting for a sinon spy, consider utilizing a stub as an alternative solution. By employing a stub, you can instruct sinon to automatically invoke any function parameters it receives.

window.$script = sinon.stub();

// set up the stub to automatically trigger any supplied callbacks
window.$script.yields();

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

Using Jquery to Insert Numbers Inside Brackets to Selection

I am struggling to calculate the sum of numbers in jQuery for selection fields. Currently, my code looks like this. $(function() { $("select").change(function() { updateTotal(); }); updateTotal(); }); function updateTotal() { ...

Utilize JQuery variables for toggling the visibility of various DIV elements

On my webpage's splash page, there are 4 divs but only the home div is initially visible. The other three are hidden. Each of these divs has a button associated with it that triggers a jquery click event to swap out the currently visible div for the ...

I am struggling to create a modal component for a settings button

I am currently working with Quasar VueJS and I have a requirement to add a button on my navbar that will trigger a pop-up dialog settings panel. This settings panel will be used for various functionalities such as dynamic theming, although that is somewhat ...

What could be causing the sluggishness in my jQuery script that checks for required input fields?

My goal is to utilize jQuery to check for required input fields in browsers that do not recognize the required HTML tag. Below is the jQuery script I am using. $('div').on('submit', '#myform', function(e){ e.stopProp ...

Tips for accessing touch events within the parent component's area in React Native

I implemented the code below in my React Native app to disable touch functionality on a specific child component. However, I encountered an issue where the touch event was not being detected within the area of the child component. How can I fix this prob ...

Executing an AJAX request with a specific state in Node.js

Instead of rendering add.jade directly, I have chosen to enhance the user experience by making an AJAX call to the endpoint. This allows me to maintain the URL as localhost:3000/books, rather than localhost:3000/books/add which lacks navigation state for ...

The JOI validation process is failing to return all error messages, even though the "abort early" option

I have been encountering an issue while trying to validate my payload using a joi schema. Instead of returning the errors specified in the schema, only one error is being displayed. Even when I provide a payload with name as "int", it only shows one custom ...

Inject Custom ASP Control Script into the DOM dynamically upon registration

During a postback, I am loading my ascx control when a dropdown change event occurs. Parent C#: private void ddlChange() { MyControl myCtr = (CallScript)Page.LoadControl("~/Controls/MyControl.ascx"); myCtr.property = "something"; // setting publ ...

A step-by-step guide on initializing and setting a cookie value with expiration

Below is the code I have added. Can someone please help me locate the bug? Here is the code snippet: $_SESSION['browser'] = session_id(); setcookie($expire, $_SESSION['browser'], time() + (60 * 1000), "/"); echo "Value is: " . $_COO ...

Creating a clickable link that dynamically updates based on the span and id values, and opens in a new browser tab

I am attempting to create a clickable URL that opens in a new window. The URL is being displayed and updated on my HTML page in the following manner: Python Code: def data_cb(): return jsonify(waiting=await_take_pic()) Javascript Code: jQuery(d ...

When resizing an anchor tag with a percentage in CSS, the child image width may not scale accordingly

In short, I have multiple draggable images on a map enclosed in anchor tags (<a><img></a>) to enable keyboard dragging. The original image sizes vary, but they are all too large, so I reduced them to 20% of their original sizes using the ...

An issue occurred while trying to use the next() method with passport.authenticate('local') function

My current middleware setup involves the use of passport.js for user authentication before moving on to the next middleware: exports.authenticate = (req, res, next) => { passport.authenticate('local', (err, user, info) => { console.l ...

Translating Encryption from Javascript to Ruby

I have an application which utilizes HTML5 caching to enable offline functionality. When the app is offline, information is stored using JavaScript in localStorage and then transmitted to the server once online connectivity is restored. I am interested in ...

What is the best way to limit the length of text in a div if it surpasses a

As I work on a website, users have the ability to add headings to different sections of a page. For example: M11-001 - loss of container and goods from Manchester Some headings can be quite detailed, but in reality, only the first few words are needed to ...

Error in compiled.php on line 7772: Laravel throwing a RuntimeException when sending HTTP requests from Angular

Hey there, I've been encountering an error intermittently while using Angular $http methods with a Laravel API. Can someone please explain what this error means and suggest potential solutions? I've shared the error log on CodePen for easier refe ...

What is the best way to showcase a specific column from a dataset using Vue.js and axios?

Hey there, I'm still getting the hang of all this and haven't quite mastered the jargon yet. Here's what I need help with: I managed to retrieve data from my SQL database using axios, and when I check in (f12) - network - preview, it shows: ...

Can you please explain the meaning of this statement in JavaScript/Node.js with regards to the importance of the => operator and the async and await keywords being used here?

(1) This snippet of code is used to hash a password, but the syntax may be unclear. Why does it utilize async and await in this manner? And why doesn't the => symbol seem to define a function? const hashPassword = async password => await bcrypt ...

What is the best way to access the URLs of files within a Google Drive folder within a React application?

I've been working on a react app that's relatively straightforward, but I plan to add a gallery feature in the future. To keep things simple for the 'owner' when updating the gallery without implementing a CMS, I decided to experiment ...

saving user's scroll position in a Vue 3 app

Encountering an issue with my Vue application. It comprises more than 40 pages, and the problem lies in the browser caching the scroll position. As a result, when users navigate from one page to another, the browser displays the scroll position of the prev ...

Is it possible to create a table using a loop in an SQLite query?

Welcome In the company where I work, Excel is currently being used to manage a large database of items for cost estimation purposes. To simplify this process, I am developing an Electron App that will replace Excel with a more user-friendly interface and ...