Simulated static functions are invoked within the main function under evaluation

Looking to mock certain functions within a function I'm currently testing.

In my code, there is a class with various static private functions that are called by the main function. Specifically, I want to verify the output of MyClass.functionD (which is invoked by mainFunction, a private method). To do this, I aim to mock MyClass.functionA, MyClass.functionB, and MyClass.functionC to return default results, allowing me to focus on the outcome of MyClass.functionD in my test.

export default class MyClass {

   static mainFunction(paramA: string, paramB: number): boolean {

        if (MyClass.functionA(paramA, paramB)) {
            return false;
        }

        if (!MyClass.functionB(paramA, paramB)) {
            return false;
        }

        if (MyClass.functionC(paramA, paramB)) {
            return false;
        }

        // Need to concentrate on the result of this private function for testing
        if (MyClass.functionD(paramA)) {
            return false;
        }

        return true;
   }

}

I've experimented with jest spyOn and default mock functions but feel stuck due to my limited experience with TypeScript/Javascript. Any pointers or references on how to proceed would be greatly appreciated! Thanks in advance.

Answer №1

The TypeScript public and private keywords are used for code validation purposes only and do not affect the JavaScript output. You can still access these private methods using bracket notation like MyClass['functionA'] to ignore TypeScript's type checking. This allows you to mock these private methods using jest.spyOn.

For your testing strategy, consider the following:

MyClass.ts:

export default class MyClass {
  static mainFunction(paramA: string, paramB: number): boolean {
    if (MyClass.functionA(paramA, paramB)) {
      return false;
    }

    if (!MyClass.functionB(paramA, paramB)) {
      return false;
    }

    if (MyClass.functionC(paramA, paramB)) {
      return false;
    }

    if (MyClass.functionD(paramA)) {
      return false;
    }

    return true;
  }

  private static functionA(a, b) {
    return true;
  }

  private static functionB(a, b) {
    return false;
  }

  private static functionC(a, b) {
    return true;
  }
  
  private static functionD(a) {
    return false;
  }
}

MyClass.test.ts:

import MyClass from './MyClass';

describe('65376946', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should pass', () => {
    const functionASpy = jest.spyOn(MyClass as any, 'functionA').mockReturnValueOnce(false);
    const functionBSpy = jest.spyOn(MyClass as any, 'functionB').mockReturnValueOnce(true);
    const functionCSpy = jest.spyOn(MyClass as any, 'functionC').mockReturnValueOnce(false);
    const functionDSpy = jest.spyOn(MyClass as any, 'functionD').mockReturnValueOnce(true);

    const actual = MyClass.mainFunction('a', 1);
    expect(actual).toBeFalsy();
    expect(functionASpy).toBeCalledWith('a', 1);
    expect(functionBSpy).toBeCalledWith('a', 1);
    expect(functionCSpy).toBeCalledWith('a', 1);
    expect(functionDSpy).toBeCalledWith('a');
  });
});

Unit test results:

PASS  examples/65376946/MyClass.test.ts
  65376946
    ✓ should pass (3 ms)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |   42.86 |       50 |      20 |   42.86 |                   
 MyClass.ts |   42.86 |       50 |      20 |   42.86 | 4,8,12,19-34      
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.168 s

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

Getting your JS project off the ground with NPM!

I am looking to develop a vanilla JavaScript project that utilizes npm packages, but I want to do it without using bundlers like Webpack. Here is a basic structure: index.html: <div id="app"></div> <script src="./index.js" type="module"&g ...

Ways to showcase contents inside a specific div when hovering with a mouse

I am working with a div structure that includes menus and items within each menu. <div id="navigate"> <div class="menu"> <div class="group">Mail</div> <div class="item">Folders</div> <div clas ...

What are some design blueprints used for conducting unit tests in Swift?

Is there a specific architectural pattern, similar to MVP or MVVM, that is commonly used for unit tests in Swift? I'm familiar with the AAA pattern, but it seems to disrupt the logic within the test method. From what I've come across, most testi ...

Vanishing ShareThis Link After Postback in JavaScript

On my webpage at , I have included a ShareThis link in the footer that is generated via Javascript. However, whenever there is an AJAX postback after entering an email on the site, the link disappears. Is there a way to prevent this from happening and ensu ...

Automatically assigning a default dynamic value to a dropdown option using Vue.js

I need to set a default selected value for the select option element, but I am facing difficulty in achieving the desired result. <template> <select v-model="tutor_work.start_year"> <option>{{tutor_work.start_year}}< ...

Why is it necessary to decode JSON stringified objects in Vue props?

When passing a stringifyed object via props to a component, it seems like there is an issue with the data transformation. <my-component :filter="stringobject" ></my-component> stringobject = "{"search_text":"(ciCl ...

Check if the <ion-content> in Angular Ionic has reached the bottom when scrolling

I'm in the process of developing a messaging app using Angular and Ionic. I want to trigger the scrollToBottom method only when it is scrolled to the very bottom. This way, if someone scrolls to the top to read old messages while their partner sends a ...

Retrieving byte data from an HTML file results in varying byte arrays across different devices

During the process of creating unit tests for a project that utilized the Razor engine to generate HTML, I encountered a peculiar issue. To ensure the accuracy of the unit test, I manually set the model, executed the function, and saved the resulting HTML ...

Using Primeng to implement pagination and lazy loading in a dataView

Looking for a way to search through product data with filters and display it using primeng dataview? Consider implementing pagination in your API that pulls products from the database page by page. Set the products array as the value in dataview so that wh ...

Interactive marker popup appearing beyond the boundaries of the map container

Our popups are set to display outside of the map container initially, but when the map is moved, they adjust to fit inside the container with the correct anchor. However, upon inspecting the DOM, we noticed that the popups do not always have the correct an ...

Pattern for identifying JavaScript import declarations

My task involves using node to read the contents of a file. Specifically, I am looking to identify and extract a particular import statement within the file that includes the "foo-bar" package. The goal is to match only the line or lines that contain the ...

What is the best way to transfer data from my browser to the backend of my application?

I am currently working on developing a basic weather application using Express and Node.js. To accomplish this, I need to automatically retrieve the latitude and longitude of the user. While I understand how to achieve this through HTML5 Geolocation in t ...

Completing the pledge using ionic/ui-routing

I've encountered an issue with my promise not resolving as expected while using Ionic/ui-routing. This is the structure of my service: return { all: function () { $localForage.getItem('foo').then(function (bar) { re ...

Pairing up with JavaScript

Currently in the process of developing a web interface for XBMC that involves ajax. Because of the limitations of our ajax functionality, I had to resort to using local resources instead of my usual ajax class which generates output. I am working with a sp ...

Unable to recognize click event within the ng-click function

I need to identify when a click event occurs on an SVG element, specifically on a g element within the SVG element. Currently, I have created this JSFiddle The ng-click function is working properly, but unfortunately, the click event is not being detecte ...

Clicking on different elements in an array using JavaScript to toggle the visibility of a div

Here is a problem I've encountered. This code selects a random element from an array to hide/show a div by toggling it. The issue is that I want it to always open a new one while hiding the previous one with the same button click. Currently, it shows ...

Angular 2 Beta Faces Issues with Loading Dynamic Routes

I am currently working on dynamically loading routes for the @RouteConfig from a service that fetches data in JSON format. [ { "path" : "/about" , "name" : "About" , "component" : "AboutComponent" }, { "path" : "/contact" , "name" : "Contact" , "compo ...

Testing the creation of elements dynamically with jestLooking into jest for dynamically adding

Attempting to test a dynamic element using TypeScript, but struggling to understand the process. Can anyone offer guidance? Below is the TypeScript file: export default class MyClass { constructor(){ this.render(); } render() { ...

How can you modify the color of a card in React by mapping through an array and evaluating its value?

I'm attempting to modify the color of a card depending on the current slot value, which is an object in an array. While I am iterating through each card, I want to adjust the background color of the card based on this value. However, my current method ...

jsonAn error occurred while attempting to access the Spotify API, which resulted

Currently, I am working on acquiring an access Token through the Client Credentials Flow in the Spotify API. Below is the code snippet that I have been using: let oAuthOptions = { url: 'https://accounts.spotify.com/api/token', method: ' ...