Unable to simulate a returned value from an import in Jest

Within my module, I have a function called shuffle<T>(a: T[]): T[] that is exported by the random module. While testing two methods in another class that rely on this function, I need to mock it. Here's how I attempted to do so:

jest.mock('./random', async () => {
  const { Foo } = await import('./Foo');

  return {
    ...jest.requireActual('./random'),
    shuffle: jest.fn().mockReturnValue([new Foo()]),
  };
});

Since mock() is hoisted, I had to dynamically import Foo within the mock() using an asynchronous approach. However, when running the actual test, I encountered the error:

TypeError: (0 , random_1.shuffle) is not a function
. It seems like all the functions from the random module were undefined.

Could this be happening because of the async import? If so, what would be the correct way to import Foo to prevent this issue with hoisting?

Answer №1

While I was reevaluating the question, a solution dawned on me. Here's my contribution in a Q&A format:

Ah yes, the issue stemmed from an asynchronous import causing the test to kick off before the Promise had resolved. To resolve this, simply place the mock inside beforeAll():

describe('A suite', () => {
  beforeAll(() => {
    jest.mock('./random', async () => {
      const { Foo } = await import('./Foo');

      return {
        ...jest.requireActual('./random'),
        shuffle: jest.fn().mockReturnValue([new Foo()]),
      };
    });
  });

  test(...);
});

Jest will patiently wait for the Promise to be resolved before proceeding with the tests.

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

What is the best way to determine the type of a key within an array of objects

Suppose I have the following code snippet: type PageInfo = { title: string key: string } const PAGES: PageInfo[] = [ { key: 'trip_itinerary', title: "Trip Itinerary", }, { key: 'trip_det ...

Tips for dealing with strong reference cycles in TypeScript?

I have created a tree-like structure in my implementation, consisting of parent and child objects. The parents contain a list of children while the children have references to their parents, facilitating easy navigation through the tree. I am now contempla ...

Display a single unique value in the dropdown menu when there are duplicate options

Hey there, I'm currently working on retrieving printer information based on their location. If I have multiple printers at the same location, I would like to only display that location once in the dropdown menu. I am aware that this can be resolved at ...

Don't forget to include the line 'import "reflect-metadata"' at the beginning of your entry point for Jest tests

As I work on developing an application using dependency injection with tsyringe, I came across a case where a service receives the repository as a dependency. Here is an example: import { injectable, inject } from 'tsyringe' import IAuthorsRepos ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

The binding element 'dispatch' is assumed to have the 'any' type by default. Variable dispatch is now of type any

I came across this guide on implementing redux, but I decided to use TypeScript for my project. Check out the example here I encountered an issue in the AddTodo.tsx file. import * as React from 'react' import { connect } from 'react-redux ...

Tips for modifying the data type of a property when it is retrieved from a function

Currently, I have a function called useGetAuthorizationWrapper() that returns data in the format of { data: unknown }. However, I actually need this data to be returned as an array. Due to the unknown type of the data, when I try to use data.length, I enc ...

Tips for concealing a parent within a complexly nested react router structure

Is there a more efficient way to conceal or prevent the rendering of parent content within a react router object? I could use conditional rendering, but I'm unsure if that's the optimal solution. My setup involves a parent, child, and grandchild, ...

angular-bootstrap-mdindex.ts is not included in the compilation result

Upon deciding to incorporate Angular-Bootstrap into my project, I embarked on a quest to find a tutorial that would guide me through the download, installation, and setup process on my trusty Visual Studio Code. After some searching, I stumbled upon this h ...

Parsing the header parameter in a GET request from Angular within the Spring backend

Recently, I delved into Rest services in Spring and learned from a tutorial that sending parameters to the backend can be done securely through the following method: getCompanyDetails(username:string): Observable<CompanyObject>{ const headers = ...

Different ways to pass a component function's return value to a service in Angular

On my HTML page, I am presenting job details within Bootstrap panels sourced from a JSON array using an ngFor loop. Each panel showcases specific job information along with a unique job ID. The panel is equipped with a click event which triggers the execut ...

Issues with style not loading properly within innerHTML in Angular2

Currently, I am in the process of developing a page using Angular2/4 that includes a left navigation bar. To achieve reusability, I have separated this left menu into its own component and nested it within the main component. The objective is to utilize th ...

What is the recommended data type for the component prop of a Vuelidate field?

I'm currently working on a view that requires validation for certain fields. My main challenge is figuring out how to pass a prop to an InputValidationWrapper Component using something like v$.[keyField], but I'm unsure about the type to set for ...

Is it possible to pass a Styled Components Theme as Props to a Material UI element?

After spending 9 hours scouring the internet for a solution, I am at my wit's end as nothing seems to work. Currently, I am developing a React component using TypeScript. The issue lies with a simple use of the Material UI Accordion: const Accordion ...

The httpClient post request does not successfully trigger in an angular event when the windows.unload event is activated

Is there a way to send a post request from my client to the server when the user closes the tab or browser window? I have tried using the 'windows.unload'or 'windows.beforeunload' event, but the call doesn't seem to be successful a ...

Having trouble implementing catchError in a unit test for an HttpInterceptor in Angular 11

I am facing challenges in completing a unit test for my HttpInterceptor. The interceptor serves as a global error handler and is set to trigger on catchError(httpResponseError). While the interceptor functions perfectly fine on my website, I am struggling ...

Adjusting the array when items in the multi-select dropdown are changed (selected or unselected)

I am looking to create a multi-select dropdown in Angular where the selected values are displayed as chip tags. Users should be able to unselect a value by clicking on the 'X' sign next to the chip tag, removing it from the selection. <searcha ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

Is there a way to make an angular component reuse itself within its own code?

I am dealing with a parent and child component scenario where I need to pass data from the parent component to the child component. The aim is to display parentData.name in the child component when parentData.isFolder===false, and if parentData.isFolder=== ...

There seems to be a lack of information appearing on the table

I decided to challenge myself by creating a simple test project to dive into Angular concepts such as CRUD functions, utilizing ngFor, and understanding HttpClient methods (specifically get and post). After creating a Firebase database with an API key and ...