Testing the throwing of errors when running Karma by utilizing sinon.spy on global functions like parseInt

I'm currently facing an issue with monitoring the usage of parseInt within my function. This is a Proof of Concept for integrating TypeScript into our company's workflow.

I've tried following two different tutorials on testing Sinon, but none of them touch upon dealing with functions from the global namespace.

Moreover, I haven't come across any discussions regarding utilizing spy on global functions except for this particular thread, which implies that it can be done.

Upon hovering over the spy function (sinon.spy(global, "parseInt")), it becomes evident that parseInt indeed belongs to the global object / namespace in TypeScript.

I have encountered this error that points to a non-existent line in the test file:

PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
  {
    "message": "SyntaxError: Unexpected token '>'\nat scripts/fortress/typescript/tests/dependencies/func.spec.ts:119:0",
    "str": "SyntaxError: Unexpected token '>'\nat scripts/fortress/typescript/tests/dependencies/func.spec.ts:119:0"
  }

When I strip away all lines except for the one where the spy is set up, the test runs smoothly.


The Proof of Concept test:

    /**
     * @description Takes two parameters and determines if they are of the same type.
     * @param {string} property A Date string (example: 'Date(1231231311231)')
     * @returns {number} A number indicating the time from epoch.
     */
export class Functions { 
    getDateNumberFromJsonPropertyString(property : string) : number {
        return parseInt(property.substring(property.indexOf("(") + 1, property.indexOf(")")));
    }
}


    describe("GetdateNumberFromJsonPropertyString", function() {
        it("should call parseInt once", function() {
            let parseIntSpy = sinon.spy(global, "parseInt"); // <-- Breaks here

            func.getDateNumberFromJsonPropertyString("(1)");    

            parseIntSpy.restore(); 
            sinon.assert.calledOnce(parseIntSpy);
        }); 
    }); 

Karma scaffolding:

/*
    KarmaJS definition file for all required unit tests.
*/

let webpackConfig = require('./webpack.config');

module.exports = function (config) {
    config.set({ 
        basePath: '',
        frameworks: ['mocha', 'chai', 'sinon'],
        files: [
            "scripts/fortress/typescript/tests/**/*.ts"
        ], 
        exclude: [
            "node_modules/"
        ],
        preprocessors: {
            "scripts/fortress/typescript/tests/**/*.ts" : ["webpack"]
        },
        webpack: {
            mode: "development",
            module: webpackConfig.module,
            resolve: webpackConfig.resolve
        },
        reporters: ["progress"],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ["PhantomJS"],
        singleRun: false,
        concurrency: Infinity
    })
}

Answer №1

Prior to making the assertion attempt, it appears that you are resetting the spy:

sinon.assert.calledOnce(parseIntSpy);
parseIntSpy.reset(); 

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

Encountering a challenge with triggering a dialog box from an onClick event on a pie chart in Angular 8 when utilizing chart.js

I am currently using a chart.js pie chart to showcase some data. I have managed to display the required information in an alert box when a slice of the pie is clicked. However, I am now looking for a way to present this data in a dialog box instead. &a ...

Using NextJS to navigate user journey by mapping an array of values from Formik to

I really appreciate all the help I've received so far, but I'm facing an issue trying to map an object with an array within it to the router. Here is my current code: const initialValues = { region: query.region || 'all', campt ...

Refresh the image source using the AJAX success callback

Previously, I was updating Label values within the AJAX success function as shown below. Now, I am looking for a way to use the same method to change or update the "src" attribute of an <img id="myimage" src=""/> $.ajax({ url: 'clmcontrol_l ...

Order of setTimeout calls in React's execution sequence

I am currently trying to wrap my head around the functionality of this React component (which is designed to delay the rendering of its children): function Delayed({ children, wait = 500 }) { const [show, setShow] = React.useState(false); React.useEff ...

Wait for the completion of a Promise inside a for-loop in Javascript before returning the response

After completing a Promise within a for-loop, I am attempting to formulate a response. Although I have reviewed these questions, my scenario remains unaddressed. The methodGetOrders and methodGetLines are components of an external library that must be ut ...

Maximizing the potential of a single .js file for multiple .html pages with AngularJS

I have a JavaScript file containing a function that I want to be accessible by multiple HTML pages without duplicating it in another file. Currently, the JS file starts with the following code snippet: (function(){ var app = angular.module('Proj ...

Removing AWS-CDK Pipelines Stacks Across Multiple Accounts

Currently, I am utilizing pipelines in aws-cdk to streamline the process of automating builds and deployments across various accounts. However, I have encountered an issue where upon destroying the pipeline or stacks within it, the respective stacks are ...

Tips for effectively changing Observable data into an Array

I am currently attempting to transform an Observable into an Array in order to loop through the Array in HTML using ngFor. The Typescript code I have now is causing some issues. When I check the testArray Array in the console, it shows up as undefined. it ...

Focus on a particular div in order to enable scrolling beyond its boundaries

Whenever I move my mouse over the div tag, I am able to scroll the content. However, if I move the mouse outside of the div box, scrolling stops. Is there a way to make the specific div element track the mouse pointer no matter where it goes? <div st ...

Access a file from a specified route within Express

Recently, I created a custom Node module that requires a configuration file in CSV format. My goal is to implement this module within an Express Route module; however, I am encountering difficulties related to the loading of the configuration file. Should ...

Ionic (Angular) experiencing crashes due to numerous HTTP requests being made

My template contains a list of items <ion-list class="ion-text-center"> <div *ngIf="farms$ | async as farmData"> <ion-item (click)="selectFarm(farm)" *ngFor="let farm of farmData" detail=&quo ...

Sending data from Django's render() method to React.js

Currently, I'm working on a Django + React Application project where I am faced with the challenge of passing JSON data from Django's render() function to React.js. To achieve this, I initiate the rendering of an HTML page using Django, with the ...

Personalized configurations from the environment in the config.json file

I need to dynamically populate a setting object in my config.json file based on environment variables. The settings should vary depending on the environment. "somesetting": { "setting1": "%S1%", "setting2": "%S2%" } I am currently working on Wind ...

Session is required for req.flash() function in node.js to work properly

I recently started working with Node.js and I'm encountering an issue with sessions. I developed a simple application and tried to run it locally, but ran into some errors. Below are the details of my code along with the error messages: BAPS.js (app. ...

Interactive input field designed for modifying, adding, and removing data in MySQL

I am working on a project where I have a simple form. However, I need to dynamically change the form action from insert to update within the same page. Additionally, I also want to display the values on the same page. Within my code, I have set up the up ...

[Vue warning]: The property "text" was accessed during rendering, however it is not defined on the current instance using Pug

Looking for some guidance from the Vue experts out there. I've recently started working with Vue and I'm attempting to create a view that verifies an email with a unique code after a user signs up. Right now, my view is set up but it's not c ...

How to automatically close the menu on a Wordpress theme after clicking a link

I am currently using a Wordpress theme named ichiban, which can be viewed by following this link. Within this theme, I have created custom menu items that are designed to link directly to different sections on the same page. However, I am encountering an i ...

Tips on how to ensure that an onClick JS function only runs when radio buttons are selected

I have implemented the formslider library for a form on my website. In the demo, the slide transitions to the next set of questions based on a click event triggered by radio buttons (answers). However, when I attempted to include checkboxes for users to s ...

Utilizing ES6 Proxy leads to the occurrence of an error message stating "this is not a function" whenever a function call

As I ventured into the depths of ES6 Proxies, attempting to be a crafty developer, I found myself entangled in their complexities. My goal was to intercept any get or set operation on a property from a class I had written and ensure that they were stored e ...

Creating a p5.js circle on top of an HTML image: A step-by-step guide

Currently, I am integrating an image into my web application using standard JavaScript and HTML. The image represents a basic map, and my objective is to utilize p5.js to draw on it. <div id="map"> <img src="Assets/MENA.jpg" ...