I seem to be encountering some errors while attempting to test promises. It appears that these tests are not yielding the expected

Despite expectations, all these specifications perform well. Witness the absurd responses generated by the delay function. I attempted to enhance code readability but unfortunately fell short.

Test spec:

describe("delay", function () {

  var chai = require("chai");
  var expect = chai.expect;
  var chaiAsPromised = require("chai-as-promised");
  chai.use(chaiAsPromised);

  var Calculator = require('C:/BaseCalculators/Calculator');
  var delay = require('C:/BaseCalculators/delay');
  var calculator;

  beforeEach(function () {
    calculator = new Calculator();
  });

  it("returns a promise", function () {
  var willAdd = delay( 100, calculator, 'add', [ 1, 1 ] );
  expect( willAdd ).to.be.instanceOf( Promise );
  expect( willAdd ).to.be.fulfilled;
  });

  it("delays execution", function () {
    expect( delay( 1000, calculator, 'add', [ 10, 5 ] ) ).to.eventually.equal( 150 );
    expect( delay( 500, calculator, 'subtract', [ 9, 5 ] ) ).to.eventually.equal( 14 );
    });

  it("cannot execute functions that do not exist", function () {
    expect( delay( 1000, calculator, 'sqrt', [ 2, 2 ] ) ).to.be.rejected;
  });
});

Calculator appears to operate smoothly with its own tests, but additional code can be added as needed. Below is the delay function which may be causing issues:

    delay = function (ms, obj, methodName, params) {
  var p = new Promise((resolve, reject) => {
      setTimeout(() => {      
        var data = obj[methodName](...params);
        console.log(data);
        p.resolve(data);
      }, ms);   
    }
  )
  return p;
}; 

module.exports = delay;

Answer №1

The issue at hand stemmed from my choice to utilize Jasmine for asynchronous tests, which ultimately proved inadequate. In an effort to resolve this, I embarked on a new project where I migrated all existing tests and JavaScript application files. Subsequently, I opted to exclusively work with mocha, chai, and chai-as-promised. To achieve this, I made adjustments to the package.json section as shown below:

"scripts": {
    "test": "./node_modules/.bin/mocha --reporter spec"

Upon execution of "npm test," everything fell into place seamlessly. Despite the unfair rating of my inquiry, I hope to reclaim some positivity by sharing this solution that may benefit others.

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 is the best method for displaying the accurate calculated value based on an element?

Within my "ROI calculator," there is a feature that allows users to adjust different labels. One of these labels is called "onlineRevenue." The concept is to recommend the most suitable plan based on the user's online revenue. However, I have some re ...

The Homescreen.js file is not showing up as expected on the localhost/home page and is not displaying

Struggling to showcase the rooms on my hotel reservation website. Can't seem to crack it. Need some assistance, please. Spent a good 3 hours trying to figure this out. Snippet from My Homescreen.js import React ,{useState, useEffect, } from &apo ...

What is the best way to enhance the class following this condition in JavaScript?

Initially, the original script worked perfectly with just one class being added: function check_btn_charge() { if (parseInt(jQuery(".total-change-price").text()) >= 0) { jQuery(".btn-action-save-charge"+" "+"btn-danger" ...

Creating a cross-platform file writer with PHP and JavaScript

My current challenge involves using buttons on an HTML page to trigger a PHP program that writes to a text file. Despite receiving a success message from my Ajax function, the file that should have been written to doesn't exist. Here's a snippet ...

Problem with JQuery binding

Currently, I have set up my radio buttons with jQuery bind using the code below: jQuery().ready(function() { jQuery("input[name='rank_number']:radio").bind('change', function(){ submitSelectedRank(); }); }); While th ...

Trouble with _.keys function in Firebug - not detecting all items

I currently have a post stored in $scope.mydata within the controller. I pass this data as a parameter to a service that returns a function. The service looks like: module.factory('myservice', function () { return function servicefunction(m ...

Gather information from a line of Javascript using Python's scraping capabilities

Is there a way to extract JSON data from a Javascript line using Python? AH4RSearch.listingsJSON = $.parseJSON('{"properties":[{"Price":3695,"PriceFormatted":"3,695","Street":"9251 E Bajada Road&q ...

Tips for incorporating a variable in a jQuery addClass method

Just starting out with jQuery and still learning. I'm attempting something seemingly simple, but struggling a bit. My goal is to customize a specific element by adding a variable in jQuery. I want to add the 'styler' class to a div with the ...

What is the best way to retrieve the current URL with a hashtag symbol using JavaScript?

I am attempting to display the current URL after the question mark with a hash symbol using PHP, but unfortunately, it is not achievable. Therefore, I need to utilize JavaScript for this task, even though I have limited knowledge of it. This is the specifi ...

Establish a many-to-many relationship in Prisma where one of the fields is sourced from a separate table

I'm currently working with a Prisma schema that includes products, orders, and a many-to-many relationship between them. My goal is to store the product price in the relation table so that I can capture the price of the product at the time of sale, re ...

Give the Row ID as a parameter to a personalized component within MUI Datagrid Pro

I am currently exploring the idea of incorporating an intermediate state to row checkboxes based on the selection status of other checkboxes within a detailed panel. My approach involves crafting a custom checkbox component and implementing some logical ...

Keep scrolling for scheduled chat availability that disables upon user engagement

Currently, I am working on developing a web Chat system that allows users to send messages to their friends. However, I am facing an issue with auto-scrolling new messages using jQuery. The pertinent files for this matter are: messages.php <div class ...

Error encountered: The use of 'import' and 'export' is limited to 'sourceType: module' when attempting to install Tweakpane

I am currently learning JavaScript and have been following a course on Domestika that requires me to install the Tweakpane package. I usually use Git Bash for installing packages, and I have successfully installed others this way before. Here is the proces ...

Encounter an issue while trying to fetch a JavaScript value from a variable using Selenium with Python

Looking to extract the value of the variable remainingTimeString from this specific webpage using Python and Selenium webdriver. I am attempting to utilize the driver.execute_script() function in my code snippet below: import selenium.webdriver options = ...

Why is it displaying undefined even though there is data stored in Firebase?

I am experiencing an issue where the datatable row is displaying "undefined" instead of the data from my Firebase database. Even when I tried inserting random data into the HTML file for the datatable, it still shows undefined. Here is a link to My Datata ...

JavaScript/AJAX Functionality Only Operates Correctly During Debugging

I am currently facing an issue with dynamically populating a website. The code works perfectly when I step through it, but it fails to work as intended on page load. Here is the relevant code snippet: <body onload="populate_all(string)";> function ...

Connecting an onclick event to trigger an external file

I have a scenario where I need to link an array of buttons with respective mp3 files. For example, if button number 5 is clicked, the 5th mp3 file should be played. How can I modify the code below to achieve this functionality? Any examples or suggestions ...

pagination functionality incorporated into element ui tables

Issue with Element UI: when a checkbox is selected and the page is changed, the selected rows' checkboxes are removed. I need to retain the selection items while paging so that users can select items from multiple pages without losing the selections f ...

Modifying a Field's Value by Referring to a Different Field

I am working on developing a form that includes a dropdown menu for changing the aircraft type. Additionally, I want to incorporate another field named "Registrations" which will automatically update the available registration options based on the selected ...

Node.js appears to experience delays following successful connection to local MongoDB

I am encountering a problem while attempting to establish a connection to my MongoDB database and fetch data from it. After the connection is established, the terminal freezes, forcing me to interrupt the process using ctrl+C. Below is the code I am worki ...