Tips for simulating difficult private attributes within a class during unit testing in TypeScript

Is there a way to mock the value of a hard private property in a unit test? For example, how can I expect something like

expect(event.getEventHis()).toBeEqual(['a', 'b'])

export class EventController {
  #event: [];
  constructor() {
    this.#event = [];
    this.#lastIndex = 0;
  }

  getEventHis(): [] {
    return this.#event;
  }

  getLastIndex(): number {
    return this.#lstastIndex;
  }

}
``

Answer №1

One way to simulate the behavior of the getEventHis() method and its output is by utilizing jest.spyOn(object, methodName).

For instance:

index.ts:

export class EventController {
  #event: string[];
  #lastIndex: number;

  constructor() {
    this.#event = [];
    this.#lastIndex = 0;
  }

  getEventHis(): string[] {
    return this.#event;
  }

  getLastIndex(): number {
    return this.#lastIndex;
  }
}

index.test.ts:

import { EventController } from './';

describe('68199289', () => {
  it('should succeed', () => {
    jest.spyOn(EventController.prototype, 'getEventHis').mockReturnValueOnce(['a', 'b']);
    const event = new EventController();
    expect(event.getEventHis()).toEqual(['a', 'b']);
  });
});

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

AJAX request made to a specific local directory, instead of the usual localhost

Currently, I am working on a project to create a database that can be filtered using various options. My approach was to keep it simple by using HTML for sliders and checkboxes, along with JavaScript/jQuery for filtering the results. This setup allows me t ...

What is the process for integrating an extension function into an Express response using TypeScript?

I am looking to enhance the Response object in Express by adding custom functions. Specifically, I want to introduce a function: sendError(statusCode: number, errorMessage: string) which can be called from anywhere like this: response.sendError(500, &qu ...

State change shows the previous and current values simultaneously

I've been working on updating the values of initUsers on the DOM. The initial state values work fine, but when I try to update initUsers, it displays different values than expected. Essentially, entriesNum receives a number as an event and changes th ...

Tips for accessing jQuery UI tab elements and adjusting visibility for specific panels

How can I retrieve the panel numbers of jQuery UI tabs and adjust their visibility using CSS? I am looking to identify the panel numbers of each tab and control the visibility of certain tabs. <div id="tabs"> <ul> <li><a href="#"> ...

What is the best way to process the bytes from xhr.responseText?

Is there a way to successfully download a large 400+ mb Json file using xmlhttprequest without encountering the dreaded Ah Snap message in Chrome due to its immense size? One potential solution I've considered is implementing setInterval() to read th ...

Tips for selecting objects based on property in Typescript?

Consider this scenario: import { Action, AnyAction } from 'redux'; // interface Action<Type> { type: Type } and type AnyAction = Action<any> export type FilterActionByType< A extends AnyAction, ActionType extends string > ...

Comparing defaultProps with the logical OR operator

Being relatively new to react, I’ve adopted a method of defining default values which looks like this: class TextInput extends Component { render() { return ( <input type="text" name={ this.pr ...

Challenges with loading content on the initial page load using the HTML5

Upon page load, I wanted to save the initial page information so that I could access it when navigating back from subsequent pages. (Initial Page -> Page2 -> Initial Page) After some trial and error, I ended up storing a global variable named first ...

Ways to adjust the positioning of an image

Seeking assistance, I am currently working on building a portfolio using HTML while following a tutorial. I utilized undraw to insert an image but unfortunately, the image is fixed to the right-hand side: I would like to position the image below my icons, ...

Using Jquery to Create a Dropdown Menu for Google Accounts

Is there a way to create a menu like Google's user account menu using jQuery or Javascript? You can find an example of this dropdown menu on the top right corner when logged in to Google. See the image below for reference. ...

Injecting services with an abstract class is a common practice in Angular library modules

In my development workflow, I have established an Angular Component Library that I deploy using NPM (via Nexus) to various similar projects. This library includes a PageComponent, which contains a FooterComponent and a NavbarComponent. Within the NavbarCom ...

The ajaxStart event does not seem to be triggering when clicked on

I am having trouble adding a loader to my site using the ajaxStart and ajaxStop requests to show and hide a div. The issue is that these requests are not being triggered by button onclick events. <style> // CSS for loader // Another class with o ...

What are the steps to increase or decrease the quantity of a product?

Is there a way to adjust the quantity of products in the shopping cart? I would like to be able to increase and decrease the quantity, while also displaying the current value in a span tag. <a href="javascript:" id="minus2" onclick="decrementValue()" ...

A guide on incorporating a JavaScript plugin using Vue.use() into a TypeScript project equipped with typings

Currently, I am facing an issue while attempting to integrate Semantic-UI-Vue into my Vue project. Upon trying to execute Vue.use(SuiVue), the following error message is displayed: Argument of type 'typeof import("semantic-ui-vue")' is not ass ...

Pagination Bug: Index Incorrectly Grabbed Upon Navigating to Next Pages

I encountered an issue with my paginated article list (105 articles with 10 per page). Everything works fine on the first page, but when I click on an article from page 2 onwards, it takes me to the index of the very first article in the array. <div cla ...

Learn the steps to retrieve a user's profile picture using the Microsoft Graph API and showcase it in a React application

I'm currently working on accessing the user's profile picture through Microsoft's Graph API. The code snippet below demonstrates how I am trying to obtain the profile image: export async function fetchProfilePhoto() { const accessToken = a ...

Container slide-show fill error

I'm attempting to create a slide show with an overlapping caption that appears when hovering over the container or image. The image needs to fit exactly inside the container so no scroll bar is shown and the border radius is correct. I managed to achi ...

Angular 5: How to Calculate the Sum of Two Numbers and Handle NaN Output

I have encountered an issue where I am trying to multiply two numbers and add another number, but the output is displaying as NaN. How can I troubleshoot and solve this problem? Below is the code snippet: medicines = [new Medicine()]; this.sum = 0;// su ...

Adding a character at the beginning of each loop iteration in a nested array with Vue.js

When working inside a v-for loop, I am attempting to add a character at the beginning of each item in a nested array that may contain multiple items. I have explored various options but have not been successful: :data-filter="addDot(item.buttonFilter ...

How to align scrolling images with their scroll origin - a step by step guide

Curious to know the name of the effect where images scroll in a different orientation than the page, creating a 2D appearance. Take a look at the Google Nexus website and scroll down - do you see the effect? What is this effect called? Is it created usin ...