Typescript's mock function allows developers to create mock implementations of

Here is the code that needs to be mocked:

const P = {
    scripts: {
        getScripts: (name?: any) => {
            // do some stuff and return json
            return { foo: 'value'};
        }
    }
}
export default P;

The code needing to be tested:

export const getScripts = (name?: string) => {
   return P.scripts.getScripts(name); // I want a mock being called here
};

I have successfully used sinonJS for my tests:

const fakeGetScript = sinon.fake.returns({
    foo: 'fakeValue'
});

However, I am struggling to replace the original getScript function of P with my fake one.

Any suggestions on how to achieve this?

Answer №1

While Proxyquire is a useful tool, it lacks the ability to maintain your typescript types. If you're looking for a solution that specifically focuses on replacing imports with fakes and is built on top of sinon, check out ts-mock-imports. This library is designed to be type safe, providing added security to your code.

Answer №2

Have you considered passing P as a collaborator to simplify the mocking process instead of intercepting require with proxyquire?

export const getScripts = (name?: string, P) => {
   return P.scripts.getScripts(name); // It would be beneficial to have a mock called here
};

// Test
const fakeGetScript = () => ({ foo: 'value' });
const P = { scripts: { getScripts: fakeGetScript } };

expect(getScripts('aName', P)).toEqual({ foo: 'value' });

Answer №3

If you find yourself needing to intercept the module creation during an import, Sinon may not be able to handle this task. A possible solution is to utilize the proxyquire library.

Here's how you could implement it:

const proxyquire =  require('proxyquire');
const fakeGetScript = sinon.fake.returns({
    foo: 'fakeValue'
});
const p = proxyquire('./path/to/p', {
  scripts: {
    getScripts: fakeGetScript
  }
});

Afterwards, you can perform your assertions on fakeGetScript as needed.

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

Excessive recursion detected in the HttpInterceptor module

My application uses JWT tokens for authentication, with a random secure string inside the JWT and in the database to validate the token. When a user logs out, a new random string is generated and stored in the database, rendering the JWT invalid if the str ...

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...

The error message "TypeError: (0 , N.createContext) is not a function" indicates that

I'm currently in the process of developing a cutting-edge application using Next.js 14, TypeScript, and Telegram Open Network. However, I've hit a roadblock while attempting to incorporate the TONConnectUIProvider at the root of my app. Upon run ...

Utilizing TypeScript code to access updatedAt timestamps in Mongoose

When querying the database, I receive the document type as a return. const table: TableDocument = await this.tableSchema.create({ ...createTableDto }) console.log(table) The structure of the table object is as follows: { createdBy: '12', cap ...

Error in Compiling HTML Elements Collection<<Element>

Currently, I am developing an eCommerce application that features a popup window for users when they click on "Add to Cart." This popup allows users to select product variations and quantities before adding the item to their cart. The popup consists of a s ...

Angular form requests can utilize the Spring Security Jwt Token to allow all options methods

Despite checking numerous sources online, I am facing a persistent issue with my Angular application. The problem arises when using HttpClient along with an Angular interceptor to set headers for authentication in my Java Rest API using JWT tokens. The int ...

Displaying Well-Formatted XML in Angular2 Using Typescript

After receiving this XML string from the server: <find-item-command xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" find-method="Criteria" item-class="com" only-id="false" xsi:schemaLocation=""> <criteria> <criterion> <descripto ...

Exploring the compatibility of Next.js with jest for utilizing third-party ESM npm packages

Caught between the proverbial rock and a hard place. My app was built using: t3-stack: v6.2.1 - T3 stack Next.js: v12.3.1 jest: v29.3.1 Followed Next.js documentation for setting up jest with Rust Compiler at https://nextjs.org/docs/testing#setting-up-j ...

Effective strategies for managing form submissions with React and Typescript

As I dive into refactoring my code to TypeScript, especially as I am still getting accustomed to it, I find myself pondering about the HTML element types with React events. This has led me to rethink how I approach form creation and submission event handli ...

Tips on identifying and handling errors without the need for type assertions in this code segment

My code is correct, but it's becoming difficult to maintain... interface FuncContainer<F extends (..._: Array<any>) => any> { func: F args: Parameters<F> } const func: FuncContainer<typeof Math.min> = { func: Math.min ...

Encountering a situation where the data retrieved from Firestore in Angular TypeScript is returning as

I am encountering an issue with retrieving the eventID value from my Events collection in Firestore. Although I am able to successfully display all the events in my app, I require the eventID for additional functionalities. As someone new to TypeScript an ...

What is the best way to retry an action stream observable in Angular/RxJS after it fails?

Kindly disregard the variable names and formatting alterations I've made. I've been attempting to incorporate RxJS error handling for an observable that triggers an action (user click) and then sends the request object from our form to execute a ...

When using react-chartjs-2 with NextJS and typescript to create a bar chart, an error occurred: TypeError - Attempting to access properties of an undefined object (specifically 'map

Encountering a console error stating TypeError: Cannot read properties of undefined (reading 'map') . As I am new to NextJS & Typescript, I am attempting to build a simple bar chart. Error message: react-dom.development.js?03cb:22839 Uncaugh ...

Array filtering functions similarly to marketplace filtering tools

In order to make the filter function like a marketplace filter, I want to only see items related to the selected brand and status. For example: partners = [ 0:{ year: "2022" badge_status: "badge-success" sale_date: "01/07/2022&quo ...

Displaying data from multiple checkboxes in an Angular application using an array

I'm currently facing an issue with displaying checked data in an Array within my Angular application. Upon clicking the checkbox, I receive a true value, but unfortunately, the data does not display as it contains null values. For reference, here is ...

Testing with mount in React Enzyme, the setState method does not function correctly

I've been experimenting with testing this code block in my React App using Jest and Enzyme: openDeleteUserModal = ({ row }: { row: IUser | null }): any => ( event: React.SyntheticEvent ): void => { if (event) event.preventDefault(); ...

What are the steps for implementing the ReactElement type?

After researching the combination of Typescript with React, I stumbled upon the type "ReactElement" and its definition is as follows: interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor< ...

What is the method to incorporate a fresh generic parameter without officially announcing it?

My goal is to define a type union where one of the types extends an existing type: // The original type type Foo<V> = { value: V; onChange: (value: V) => void }; // Type union incorporating Foo type ADT = ({ kind: "foo" } & Foo<a ...

The Route.ts file does not export any HTTP methods

Encountering an error while trying to migrate code from Next JS 12 with pages router in Javascript to Next JS 13 with TypeScript. ⨯ Detected default export in 'vibe\src\app\api\auth[...nextauth]\route.ts'. Export a name ...

Utilizing TypeScript generic types as a key for an object

function createRecord<T extends string>(key: T): Record<T, string> { return { [key]: 'asdf' }; } Encountering an issue: The type '{ [x: string]: string; }' is not matching with the expected 'Record<T, st ...