What is the best way to confirm the invocation of super in sinonjs?

My JavaScript/TypeScript class (AAA) extends another class (BBB). The API of class BBB is stable, but the implementation is not yet finalized. I just want to unit test some functions in class AAA. However, I'm facing an issue in creating an instance of class AAA due to the constructor call of class BBB. You can find an example here:

BBB.ts:

class BBB {
    constructor() {
        throw new Error("BBB");
    }
    public say(msg: string): string {
        return msg;
    }
}

module.exports = BBB;

AAA.ts:

const BB = require("./BBB");

class AAA
    extends BB {
    public hello(): string {
        return super.say("Hello!");
    }
}
module.exports = AAA;

Test Script:

const AA = require("../src/AAA");

import sinon from "sinon";

describe("Hello Sinon", () => {
    describe("#hello", () => {
        it("#hello", async () => {
            const stub = sinon.stub().callsFake(() => { });
            Object.setPrototypeOf(AA, stub);
            let a = new AA();

            sinon.spy(a, "hello");

            a.hello();

            sinon.assert.calledOnce(a.hello);
            sinon.assert.calledOnce(stub);

            // how to verify that super.say has been called once with string "Hello!"?
        });
    });
});

I'm using sinonjs. However, I'm struggling to create an instance of AAA in this case. If I can create one, I'm unsure how to verify the call to super.say.

Thank you!

UPDATE: I have managed to create an instance of AAA now, but I need guidance on how to verify the call to super.say.

Answer №1

After much research, I managed to solve the problem at hand:

describe("Testing with Sinon", () => {
    describe("#hello function", () => {
        it("should call the #hello function twice", async () => {
            const fakeFunction = sinon.stub().callsFake(() => { });
            Object.setPrototypeOf(AA, fakeFunction);
            let instance = new AA();
            const saySpy = sinon.spy(instance.__proto__.__proto__, "say");

            sinon.spy(instance, "hello");

            instance.hello();
            instance.hello();

            sinon.assert.calledTwice(instance.hello);
            sinon.assert.calledOnce(fakeFunction);
            sinon.assert.calledTwice(saySpy);
        });
    });
});

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

A technique to trigger the display of a detailed grid by clicking in the master section

Currently, I am in the process of creating a reusable master-detail grid component using Backbone. My goal is to incorporate an event that triggers the loading of the detail grid whenever a user clicks on a row within the master grid. However, I am facin ...

An issue arises even with the proper configuration in place: "SessionNotCreatedError: session cannot be established as Chrome version needs to fall within the range of 70 to 73."

During my automated testing with selenium-webdriver, I encountered an issue while building a driver using chromedriver. Everything was functioning perfectly until one day, when I ran a test and received the following error message: SessionNotCreatedErro ...

"Encountering a problem with the Flicker API while trying to view personal

I've been attempting to retrieve my personal photos using the following function with a node package obtained from this source https://www.npmjs.com/package/flickrapi\ When trying to access pictures of another user like 136485307@N06 (Apollo Im ...

The Angular ternary operator can be used in conjunction with functions for optimal

Consider this scenario: I have two functions that are triggered by a button click: <button ng-click="functionOne || functionTwo()"></button> However, I want to optimize this setup so that the functions are only called if they return a value. ...

Oops! It seems like you've stumbled upon a 404 error on Django

I need to retrieve the price value immediately after a product is selected in the sale form. The sale form includes fields for price, quantity, and product. Once a user selects a product, the price of that product should populate the input box for price. T ...

implementing firestore onsnapshotListner feature with pagination

I have a web application that needs real-time updates on a large collection of documents. However, due to the size of the collection, retrieving data without applying a limit is not feasible and inefficient. Therefore, it is crucial to implement a query li ...

Having trouble locating the 'tsc-watch' module due to the missing 'typescript/bin/tsc' when running the TypeScript compiler

Encountering the error "Cannot find module 'typescript/bin/tsc' when attempting to run tsc-watch yarn tsc-watch --noClear -p tsconfig.json yarn run v1.22.19 $ /Users/jason/Work/VDQ/VDQApp/node_modules/.bin/tsc-watch --noClear -p tsconfig.json Ca ...

Sending a request in Vue.js and not receiving a defined response

As a beginner in VueJs and Expressjs, my goal is to create the frontend using Vuejs and backend using ExpressJs. When I send a post request to the backend (ExpressJs), I encounter the following issues: 1- Response from the server is undefined. 2- In Chrom ...

I aim to conceal the Spinner feature within the service layer of Vue JS

I have a basic bootstrap Spinner.vue component <template> <div class="modal" v-if="start"> <div class="spinner-border text-info" role="status" style="width: 3rem; height: 3rem;" ...

How can we use SWR to fetch user data conditionally based on their logged-in state?

I am facing an issue with setting the UI state based on whether a user is logged in or not. The UI should display different states accordingly. I am currently using SSG for page generation and SWR for user data retrieval. However, I noticed that when call ...

Trigger animation when the scroll position reaches 0.52 in Next.js using framer-motion

I’m working on a landing page and I have a section where I’d like to create a simple opacity animation using framer-motion. The issue is that these animations typically trigger as soon as you land on the page, but I want them to be based on scroll pos ...

Sinon.js: How to create a mock for an object initialized with the new keyword

Here is the code that I am working with: var async = require('async'), util = require('util'); var Parse = require('parse/node'); function signup(userInfo, callback) { var username = userInfo.username, email ...

Choose a variety of table rows based on the values of the data attributes that are

Is there a more efficient way to select all rows with data attributes id 1,2.. without specifying each row individually? I need some guidance on the best approach for this. Can anyone help me out? <table id="eTable"> <tr data-empid="A123" data- ...

Problem with jQuery's UI autocomplete functionality

Implementing jQ UI Autocomplete with multiple values Below is how my function is structured: mailto_input.bind( "keydown", function( event ) { if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) { ...

Adjust hover effects based on true conditions

Currently working on a web app using HTML, CSS, JavaScript, and AngularJS. Progress so far includes a clickable box that triggers a javascript function to display more boxes upon click using ng-click. <div ng-click="!(clickEnabled)||myFunction(app)" cl ...

Angular 5 and the benefits of concurrent requests

My goal is to execute multiple requests in parallel, fetch the results, and combine them. To achieve this, I have implemented the following function: getStudent(query): Observable<any> { const code = this.http.get( `http://localhost ...

Everything runs smoothly when initiating the API call through npm start, but unexpectedly crashes upon attempting to

Here is an API call located at http://localhost:9000/testAPI. Within the bin/www file: var port = normalizePort(process.env.PORT || '9000'); app.set('port', port); Inside the routes/index.js file: var express = require('express&a ...

Retrieve information using the request npm package

Currently, I am in the process of developing an application with express js. My approach involves using request(v-2.88.2) to retrieve data from an api. request(url, function(error, request, body) { var data = JSON.parse(body); }); My goal is to utili ...

Displaying empty values as zeros

Currently, I am creating a chart using Morris js. The data for the chart comes from a server and consists of dates and values. However, there are cases where certain dates do not exist in the data set. In such situations, I want to display these non-existe ...

Unable to update the React state on a component that is unmounted when using HOOK

I'm currently working on a user authentication code in React, specifically for an Expo project. function App(){ const [user, setUser] = useState(null); if (user){ return <Dashboard user={user} /> } return <Authentication ...