Experimenting with the static method within a singleton class using Typescript and Sinon

I have a separate layer in my application that uses a DAO class to retrieve data from the repository. I've implemented the DAO class as a Singleton and made its methods static.

In another class, I've created service methods to manipulate the data obtained from the DAO. However, I'm having trouble writing tests for this code.

How can I mock the DAO repository methods?

This is what I have attempted so far:

// error: TS2345: Argument of type "getAllPosts" is not assignable to paramenter of type "prototype" | "getInstance"
const dao = sinon.stub(Dao, "getAllPosts");

// TypeError: Attempted to wrap undefined property getAllPosts as function
const instance = sinon.mock(Dao);
instance.expects("getAllPosts").returns(data);

export class Dao {

    private noPostFound: string = "No post found with id";
    private dbSaveError: string = "Error saving to database";

    public static getInstance(): Dao {
        if (!Dao.instance) {
            Dao.instance = new Dao();
        }
        return Dao.instance;
    }

    private static instance: Dao;
    private id: number;
    private posts: Post[];

    private constructor() {
        this.posts = posts;
        this.id = this.posts.length;
    }

    public getPostById = (id: number): Post => {
        const post: Post = this.posts.find((post: Post) => {
            return post.id === id;
        });

        if (!post) {
            throw new Error(`${this.noPostFound} ${id}`);
        }
        else {
            return post;
        }
    }

    public getAllPosts = (): Post[] => {
        return this.posts;
    }

    public savePost = (post: Post): void => {
        post.id = this.getId();

        try {
            this.posts.push(post);
        }
        catch(e) {
            throw new Error(this.dbSaveError);
        }
    }
}

Answer №1

Here's how I tackled the problem:

// instantiate a Singleton object
const singleObject = Database.getInstance();

// create a mock for the object
const mockDatabase = sinon.mock(singleObject);

// mock the "getAllData" method
mockDatabase.expects("getAllData").returns(data);

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

The Data Table experiences intermittent hanging issues (Table is empty) when sorting or loading data with Knockout binding

While working on a project, I encountered an issue with binding data to a table using Knockout JS and the JQuery/Bootstrap based; Data Table API. The problem was that the table would become unresponsive at times when sorted or loaded, without any errors be ...

Using embedded js files in jQuery's .load() function does not function properly

In the index.html file, I have the code snippet below: <div id="page-insert"></div> function openPage(pageid) { $('#page-insert').load(pageid); } openPage('testpage.html'); Additionally, there are script files embedde ...

Arrange elements within an array according to a specific property and the desired sorting sequence

Looking for a way to sort an object array in Angular 16+ based on status. The desired status order is: [N-Op, Used, Unknown, Op] Here's the sample data: const stockList = [ { 'heading': 'SK', 'status': &a ...

Obtaining values from event listeners in Vue.js across different methods

Looking for guidance on the code snippet provided below. Is there a way to assign the value of "e.detail.name" to "nodeName," and then access it in a different method within the component for an API request? data() { return { nodeName: '' ...

Validating the download dialog window with selenium

I'm currently working on a website and using selenium for integration testing. On the page, there is a link that is created using various variables. I want to make sure that when I click on this link to download a file, the download pop-up box appear ...

Having difficulty retrieving additional arguments within createAsyncThunk when dispatched

When attempting to update the user thunk action by passing an axios instance as an extra argument, I am encountering difficulties in accessing the extra argument. Despite being able to access other fields such as getState</coode> and <code>disp ...

Steps to display the datatable footer on the printed page

I am having trouble understanding the solutions provided for my table query. The current table setup is as follows: <table class="table table-bordered make_datatable"> <thead> <tr> <th>SL No</th> ...

Can we incorporate modulo into the loop?

I have a JavaScript function with HTML code inside. I need the ".one-card" div to repeat four times within each ".row" div. The ".row" div is being repeated in a foreach loop. I want to check if the result of modulo (4) is not equal to zero, then display t ...

Is there a way for me to extract the true text content that is concealed within the page source code?

Is there a way to extract the hidden text "2015-10-31" from a webpage, even though it is not visible in the page source? I am able to scrape the right side of the HTML, but I need to access the value on the left side. I have tried using Selenium to automat ...

Display JSON data values using jQuery

After receiving my data from Json, I am having trouble displaying it. Below is the javascript code snippet: jQuery( document ).ready( function( $ ) { $('select[name="country_id"]').on('change', function() { $.ajaxSetup({ ...

JavaScript codes within HTML elements may not be functional when using an AJAX loader to transition to the next page

I'm experiencing issues with an ajax loader in Wordpress. The theme I am using has an ajax loader button that is interfering with my inline script. Despite reading over 10 articles on the problem, I haven't been able to find a solution yet. Do ...

"Receiving an 'undefined index' error when attempting to post in Ajax with

Need help with sending data from client to server using AJAX in PHP. I am facing an issue when trying the following code: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascrip ...

What seems to be the issue with loading this particular file into my JavaScript code?

When attempting to import a file into my code, I encountered an issue where the folder could not be found. Interestingly, when manually typing out the folder name, it is recognized and suggested by the system. Even providing the full path did not yield dif ...

What are some strategies for optimizing speed and efficiency when utilizing jQuery hover?

While developing a web application, I have created a grid using multiple div elements that are X by Y in size, determined by user input. My goal is to change the background color of surrounding divs within a certain distance when hovering over one particul ...

There are currently no articles found that match the search query

Recently, I started working with Django, but I am facing an issue with slug. Whenever I send a request to the Slug, I encounter an error. The error message I receive is: Articles matching query does not exist. Furthermore, I am facing another error while ...

Issue with express-validator returning undefined value on forms set to enctype='multipart/form-data'

Currently, I am developing a login authentication application using basic node.js+express. While extracting values (such as name, email, etc) from the registration page, I utilize express-validator for validation. However, I encounter an issue where all va ...

Executing a keystroke in Selenium Webdriver using JavaScript

I've been writing a test using Selenium WebDriverJS, and now I need to simulate pressing a key on the keyboard. Is it possible to do this with Selenium WebDriverJS? If so, how can it be done? In Java, we achieve this as follows: driver.findElement(Lo ...

Extracting and retrieving the value from the paramMap in Angular/JavaScript

How can we extract only the value from the router param map? Currently, the output is: authkey:af408c30-d212-4efe-933d-54606709fa32 I am interested in obtaining just the random "af408c30-d212-4efe-933d-54606709fa32" without the key "authke ...

What is the reason behind the removal of the "disabled" attribute when setting the "disabled" property to false?

Initially, I have a disabled button: <button disabled="disabled">Lorem ipsum</button> When using button.getAttribute('disabled'), it returns "disabled". But once the button is enabled with JavaScript: button.disabled = false; The ...

Show information from an array

On the index.php page, there is a script that retrieves data from demo.php and presents the outcome in a div. <div class="leftbox"> <?php echo "<div id='proddisplay'>"; echo "</div>"; ?> </div&g ...