Is it feasible to mock a defined function in Typescript for a unit test scenario?

Currently, I am working on typescript code that compiles into javascript, gets bundled with rollup, and is utilized by a framework. This framework exposes a library to me in the global scope, taking the form of a function:

    fun({
      prop1: number,
      ...
    });

I do not want to include this library in my bundled JavaScript as it is already provided by the framework. Having different versions of the library could potentially lead to unexpected bugs. In my opinion, it would be safer and more straightforward to use the library supplied by the framework.

After some research, I believe the declare keyword serves this purpose. So, I added the following line in the same file where I call fun:

export declare function fun(input: unknown): void;

Although my code now compiles successfully, I am facing challenges when it comes to unit testing. When attempting to test the code that calls fun, Jasmine reports an error saying:

ReferenceError: fun is not defined

While I understand the reason for this error, I am unsure how to circumvent it. I tried using sinon to stub fun, but encountered a similar issue during testing with Jasmine.

The solution I came up with involves adding an if statement around the call to fun in order to skip it during testing - a workaround that I'm not fond of.

I am seeking advice on how to properly stub fun so that I can execute the code calling it and verify that the correct properties are being passed. Alternatively, is there a way to create a mock version of fun that can be excluded from the transpiled javascript for testing purposes, yet does not exist in production? Due to module functionality, I am doubtful about this possibility, but I am open to exploring any suggestions.

Answer №1

This method has proven to be effective for me. If anyone knows of a superior or simpler approach, I am open to learning about it.

    // within a certain file (ensure there is an import/export in order for it to compile correctly)
    declare global {
      interface Window {
        fun: (input: unknown) => void;
      }
    }
    
    // during the testing phase
      beforeEach(() => {
        sandbox = sinon.createSandbox();
        window.anime = sandbox.stub();
      });
    
      afterEach(() => {
        window.anime = ... // This step is optional. Restore it to its original state
      });
    
    // somewhere in a test case
       expect((window.fun as SinonStub).callCount).toBeGreaterThan(0);

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

How to access enums dynamically using key in TypeScript

export enum MyEnum{ Option1, Option2, Option3 } string selection = 'Option1'; MyEnum[selection] results in an error: The type string cannot be assigned to the type MyEnum On the other hand: MyEnum['Option1'] works as ...

Experiencing an issue when attempting to deploy Strapi CMS with TypeScript on Railway - encountering the error message: "Unable to locate module 'typescript'"

Issue with Deploying Strapi CMS in TypeScript to Railway Currently facing challenges while trying to deploy Strapi CMS written in TypeScript to Railway. Despite the availability of a JavaScript template, there's a lack of a specific TypeScript templa ...

What is a creative way to design a mat-radio-group without traditional radio buttons?

I am looking to create a component that offers users a list of selections with the ability to make only one choice at a time. The mat-radio-group functionality seems to be the best fit for this, but I prefer not to display the actual radio button next to t ...

When calling undefined typescript, the async function does not return a value but displays its result afterwards

When I debug my function, it waits until the return statement, but when I call the function, it returns undefined and the errors are also undefined. I'm not sure why this is happening. import userModel from '../Models/user.model'; const bcr ...

Change a TypeScript alias within the @types namespace

While using Typescript 3, I encountered a situation where I needed to modify a type alias from the @types/json-schema definition provided by DefinitelyTyped. The issue arose when I wanted to incorporate a custom schema type into my code. Since this custom ...

Angular 5 - Creating a dynamic function that generates a different dynamic function

One of my latest projects involved creating a versatile function that generates switch-case statements dynamically. export function generateReducer(initialState, reducerName: ReducerName, adapter: EntityAdapter<any>): (state, initialState) => ISt ...

Node path response not being properly configured

Just diving into the world of node and typescript and could use a bit of guidance. Currently utilizing node/express/postres as backend and leveraging https://github.com/typeorm/typeorm as an orm, which offers a function to open a connection structured as f ...

What is the method for adding local images to FormData in Expo version 48 and above?

When working with Expo v47 and its corresponding React Native and TypeScript versions, FormData.append had the following typing: FormData.append(name: string, value: any): void An example of appending images using this code could be: const image = { uri ...

Identifying misspelled names in shared resources textures during PIXI.js loading

Our game utilizes TypeScript, Pixi.js, VSCode, and ESLint. We maintain a dictionary of image files as follows: export function getAllImages(): {name: string, extension: string}[] { return [ {name: 'tile_lumber', extension: '.svg ...

Ensure that the query value remains constant in Express.js

Issue: The query value is changing unexpectedly. // url: "http://localhost:4000/sr?q=%C3%BCt%C3%BC" export const search = async (req: Request, res: Response) => { try { const query = String(req.query.q) console.log("query: &quo ...

Retrieve user information by their unique user ID from a MongoDB database using a Node, Express, and TypeScript API

Currently, I am working on a Node JS and Express with TypeScript API project. In this project, I need to retrieve data stored by a specific user from MongoDB based on their user ID. This is a snippet from my DataRouter.ts: router.get('/:userId', ...

The efficiency of React Context API's setters is remarkably sluggish

I have a goal to implement a functionality where the background gradient of a page changes depending on whether the child's sublinks are expanded or collapsed. To achieve this, I am using the useContext hook. However, I've noticed that although e ...

Validators in Angular forms are a powerful tool for enforcing

Is it possible to use Validators in the ts.file to display an error message when a field is invalid, rather than directly in the html? Thanks. html <form [formGroup]="form"> <mat-form-field> <mat-label>Nom</mat-label> ...

Defining the type of the createAction() function in TypeScript within the context of Redux Toolkit

Lately, I have been delving into the redux-toolkit library but I am struggling with understanding the type declaration of the createAction function as demonstrated below. The createAction function returns a PayloadActionCreator which includes a generic of ...

AngularFire2 Firestore Custom Query: retrieve documents based on current date and time.startTime

Welcome to the world of AngularFire2 and Firestore! My objective is clear: Query data from Firestore where startTime matches currentDateRange. I am facing some challenges with creating a dynamic query in Firestore. After going through the official docume ...

Get an angular xml file by utilizing the response from a C# web API download

I am trying to download an XML file from a database using a Web API in C#, which returns the file as byte[]. How can I properly read these bytes and convert them into an XML file on the client side using Angular? Despite attempts with blobs and other metho ...

Encountering an issue with MUI 5 where it is unable to access properties of undefined when utilizing makestyles

I recently finished building a react app using MUI-5 and everything was running smoothly. However, I've encountered a strange issue where my app refuses to start and I'm bombarded with multiple MUI errors. These errors started popping up after I ...

Mapping a TypeScript tuple into a new tuple by leveraging Array.map

I attempted to transform a TypeScript tuple into another tuple using Array.map in the following manner: const tuple1: [number, number, number] = [1, 2, 3]; const tuple2: [number, number, number] = tuple1.map(x => x * 2); console.log(tuple2); TypeScript ...

What could be causing the issue of CSS Styles not being applied to an Angular 2 component with Vaadin elements?

Currently, I am immersed in the tutorial on Vaadin elements using Angular 2 that I stumbled upon here In section 5.3, Styles are applied to the app.component.ts as shown below import { Component } from [email protected]/core'; @Component({ select ...

What is the best way to evaluate typing into an input field?

My objective is to test the 'typing' functionality in an input element. The aim is to insert a value into the input element, verify that its binding successfully captures the value, and observe the entered value within the input element. Below i ...