Can inner function calls be mimicked?

Consider this scenario where a module is defined as follows:

// utils.ts
function innerFunction() {
  return 28;
}

function testing() {
  return innerFunction();
}

export {testing}

To write a unit test for the testing function and mock the return value of

innerFunction</code, you can specify a fixed value for any call to <code>innerFunction
. This can be achieved using the following code snippet:

jest.mock('../utils', () => {
  const originalModule = jest.requireActual('../utils');

  return {
    ...originalModule,
    innerFunction: jest.fn().mockReturnValue(33),
  };
});

import { testing } from '../utils';

it('should validate properly', () => {
  expect(testing()).toBe(33);
});

Despite the expectation that jest.requireActual would read all functions and set

innerFunction: jest.fn().mockReturnValue(33)</code to always return <code>33
, it doesn't seem to work in practice based on the provided experiment.

In reality, innerFunction returns 28, but within Jest environment, we hope to control innerFunction to resolve to the desired value.

Answer №1

Choice 1

Consider passing innerFunction as a parameter to function testing

utils.ts

function testing(innerFunction: () => number)  {
  return () => innerFunction();
}

export {testing}

test.ts

import { testing } from '../utils'  
  it('everything should work fine', () => {
    const mock = () => 33

    // Also known as SUT (System under test)
    const sut = testing(mock)

    expect(sut()).toBe(33);
  });

Unit tests can be simplified without jest, and are also more reliable...

Choice 2

Relocate innerFunction into a separate file, and utilize jest.mock

innerFunction.ts

export function innerFunction()  {
      return 33
}

utils.ts

import { innerFunction } from './innerFunction.ts'

function testing()  {
    return innerFunction();
}

export { testing }

test.ts

jest.mock('./innerFunction', () => {
  return () => 33
});

import { testing } from '../utils'

  it('everything should work fine', () => {
    expect(testing()).toBe(33);
  });

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

In MUI v5, the Autocomplete default value is not set

When I try to use the defaultValue prop in the Autocomplete component of MUI v5, the value always ends up being undefined. This is a snippet from my code: const vehicles = [ { name: "Toyota", model: "Camry" }, { name: "Ford&qu ...

The Typescript errors is reporting an issue with implementing the interface because the type 'Subject<boolean>' is not compatible with 'Subject<boolean>'

Creating an Angular 2 and Typescript application. I am facing an issue with an abstract class within an NPM package that I am trying to implement in my app code. Everything was functioning correctly until I introduced the public isLoggedIn:Subject<bool ...

Generating npm package without including file extensions in imports

I am currently working on creating an internal library for my workplace. Everything seems to be going smoothly until I try to use it in another project. It appears that the file extension in all of the import statements has disappeared during the npm pack ...

Issues with setting headers after they have been sent - Can you explain why?

How am I setting a header after it has been sent to the client? Here is the code snippet: When a form is submitted, a post ajax request is triggered which returns a JSON object to the client. I have commented out most of the code to troubleshoot, and cur ...

Show each text field individually in JavaScript

Is it possible to display text fields one by one upon button click? Initially, all text fields are hidden, but when the button is clicked, they should be displayed one after another with their visibility property set to visible? This is what I have attemp ...

Connecting Angularfire2 with Firestore for advanced querying

Glad you stopped by! Currently, I have two Firestore Collections set up in my Angularfire2 application. One consists of "Clients", while the other contains "Jobs". Each client can have multiple jobs assigned to them, and vice versa. I've been workin ...

The scale configuration for scale: x is not valid for creating a time scale chart using chart.js

I am currently utilizing VueJS and attempting to integrate a time scale chart using Chart.js. However, I encountered the following error: Invalid scale configuration for scale: x Below is my configuration : First, I have a component named Chart.vue with ...

The A-Frame buffer geometry merger may cause unexpected entity shifts under certain circumstances

My A-Frame scene has a simple issue with the buffer-geometry-merger component. It works perfectly fine when entities are written in static HTML, but not when injected into the DOM using an A-Frame component. It seems like the geometry gets shifted, as if t ...

I'm looking for a streamlined method to simultaneously access multiple APIs with GraphQL and React

For my client side project, I'm using GraphQL and React but opting not to use Redux for state management. Instead, I have organized my API calls into custom hook files as shown below: const [getSomeData, { data: getSomeDataData, loading: getSomeData ...

Opting for Mysql over MongoDB as the provider in Next.js with Next-auth

Exploring the Next.js framework for the first time, I've dived into using Next-auth to handle sign-up/login functionality based on the provided documentation. My experience so far has been smooth, especially with the MongoDB provider as recommended i ...

What could be causing the "buffer is not a function" error to occur?

As a beginner with observables, I'm currently working on creating an observable clickstream to avoid capturing the 2 click events that happen during a double-click. However, I keep encountering this error message:- Error: Unhandled Promise rejection ...

What is the best way to output data to the console from an observable subscription?

I was working with a simple function that is part of a service and returns an observable containing an object: private someData; getDataStream(): Observable<any> { return Observable.of(this.someData); } I decided to subscribe to this funct ...

Using AngularJS to access JSON files through the $http service

I'm experiencing difficulties reading data from my test.json file using the #http service. I have everything set up on a xampp localhost, but I can't seem to figure out what's going wrong. Here's the JavaScript code. Thank you in advanc ...

Step-by-step guide on generating a downloadable file in Vue

As a beginner in Vue, I am tasked with downloading a file but unsure of how to proceed. My attempt at the code resulted in the image opening on a new page instead. <a class = "btn btn-success btn-xs" href = "https://78.media.tumblr.com/tumb ...

Is it recommended to incorporate router.isReady when making requests with react-query?

Struggling with incorporating react-query into my codebase, currently using getStaticProps. Experimenting with router.isReady from next/router to ensure the page waits for router.query value before passing it as props to the react hook. Take a look at my ...

Showing data related to a certain value - what's the best way?

I am currently working on a page where I need to display and edit specific user information at /users/524.json. However, I also want to include the working days from another table on the same page. I have provided most of the code below for reference. Unfo ...

What is the proper way to include type annotation in a destructured object literal when using the rest operator?

When working with objects, I utilize the spread/rest operator to destructure an object literal. Is there a way to add type annotation specifically to the rest part? I attempted to accomplish this task, but encountered an error when running tsc. const { ...

Once the Ajax request is finished, the cookie deletion function ceases to function

When the website loads, a cookie is generated using PHP before any other content or headers are sent. This is done with the following code: $steam_login_verify = SteamSignIn::validate(); if(isset($_COOKIE['userid'])) { //work with cookie va ...

Utilize SWR in NextJS to efficiently manage API redirection duplication

When using SWR to fetch data, I encountered an error where the default path of nextjs was repeated: http://localhost:3000/127.0.0.1:8000/api/posts/get-five-post-popular?skip=0&limit=5 Here is my tsx code: 'use client' import useSWR from &quo ...

How can you determine if all specified events have been triggered in jQuery?

I am implementing custom triggered events following asynchronous calls, and I'm in need of a method to determine when all the events have been triggered. For instance: var ajaxCall1 = function(){ $.ajax({ url: "someUrl.html", com ...