Is there a way to pass around jest mocks across numerous tests?

In my test scenarios, I've created a mock version of the aws-sdk, which is functioning perfectly:

jest.mock("aws-sdk", () => {
  return {
    Credentials: jest.fn().mockImplementation(() => ({})),
    Config: jest.fn().mockImplementation(() => ({})),
    config: {
      update: jest.fn(),
    },
    S3: jest.fn().mockImplementation(() => ({
      getSignedUrlPromise: awsGetSignedUrlMock,
    })),
    SQS: jest.fn().mockImplementation(() => ({})),
  };
});

However, my various tests rely on this mocked AWS SDK, and I want to avoid duplicating the code unnecessarily. When attempting to move this function into a separate file for import, I encounter an issue:

Within my testSupport.ts file:

export const mockAwsSdk = () => {
  return {
    Credentials: jest.fn().mockImplementation(() => ({})),
    Config: jest.fn().mockImplementation(() => ({})),
    config: {
      update: jest.fn(),
    },
    S3: jest.fn().mockImplementation(() => ({
      getSignedUrlPromise: awsGetSignedUrlMock,
    })),
    SQS: jest.fn().mockImplementation(() => ({})),
  };
};

When trying to use this in the test file:

jest.mock("aws-sdk", mockAwsSdk);

This results in the following error:

ReferenceError: Cannot access 'testSupport_1' before initialization

I have experimented with different approaches, including creating a parent function that accepts the jest instance, but I have not yet found a solution.

Is there a way to efficiently share jest mocks across multiple tests?

Answer №2

I encountered a similar issue and managed to resolve it by utilizing the setupFiles feature.

To address this, you can establish a jest.config.js file:

const configuration = {
  setupFiles: ['./src/setupFiles.js']
}

export default configuration

You can then proceed to define your shared mocks within the setupFiles.js:

import { Logger } from 'from-some-package'

jest.spyOn(Logger, 'init').mockImplementation(() => jest.fn())
jest.spyOn(Logger, 'info').mockImplementation(() => jest.fn())
jest.spyOn(Logger, 'debug').mockImplementation(() => jest.fn())
jest.spyOn(Logger, 'error').mockImplementation(() => jest.fn())

jest.mock('third-party-package');

global.fetch = jest.fn()

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

Embed HTML code into a React/Next.js website

I've been given the task of enhancing the UI/UX for an external service built on React (Next.js). The company has informed me that they only allow customization through a JavaScript text editor and injecting changes there. However, I'm having tro ...

Tips for stopping webpack from creating compiled files in the source directory

I'm in the process of transitioning my AngularJs project from ES6 to TypeScript and I've integrated webpack with ts-loader. However, I've encountered an issue where the compiled files and source maps are saved in my directory instead of bei ...

Open multiple accordion sections simultaneously

In my current setup, I have a paginated loop of elements that contains an accordion. The accordion is implemented using angular-ui-bootstrap. <div data-ng-repeat="m in results"> <div class="stuff_in_the_middle"> <accordion id="a ...

How can we define a function using a generic type in this scenario using Typescript?

Here's a challenge that I'm facing. I have this specific type definition: type FuncType<T> = (value: T) => T I want to create a function using this type that follows this structure: const myFunc: FuncType<T> = (value) => valu ...

Steps for breaking down a given string into divisions that correspond to an A4 sheet

Within my content, there are various styles applied. For example: This is a <b>bolded</b> word. I am seeking a solution to divide this long string into smaller sections that would fit on an A4 page accurately. The goal is to maintain the integ ...

Next.js: Generating static sites only at runtime due to getStaticProps having no data during the build phase, skipping build time generation

I am looking to customize the application for individual customers, with a separate database for each customer (potentially on-premise). This means that I do not have access to any data during the build phase, such as in a CI/CD process, which I could use ...

I want to know how to showcase elements from a list one by one and cycle through them using a button with a nodejs server and Pug

As someone who is brand new to Web development, NodeJs servers, and Pug, this is my first time diving into any of these technologies. My goal is to create a dynamic box (in the form of a div) that changes its content based on a list from a JSON file. Initi ...

Upon attempting to start the server, the module 'express-stormpath' could not be located

Upon trying to execute node server.js (in a regular terminal without superuser or root permissions), the following error is thrown: alphaunlimitedg@AUNs-PC:~/my-webapp$ node server.js module.js:442 throw err; ^ Error: Cannot find module 'expr ...

What is the correct way to integrate $.deferred with non-observable functions?

Imagine you have two functions filled with random code and the time they take to complete is unknown, depending on the user's system speed. In this scenario, using setTimeout to fire function2 only after function1 finishes is not practical. How can j ...

The provider named toasterProvider is not recognized within the dependency injection chain, which includes toaster, RugHttpInterceptor, $http, and ng1UIRouter

Working with Interceptors to show a toast message when my app encounters an HTTP error in responseError code. Using AngularJS Interceptor for an MEAN.JS app. Interceptor Code angular.module('rugCoPro') .factory('RugHttpInterceptor', ...

Integrating Dynamics CRM with an External Source to Trigger Workflows

Scenario: Imagine a scenario where you want to trigger an existing workflow or a custom action from a webpage located outside the CRM Dynamics environment, such as MS CRM 2011-2013-2015-2016 and 365. Potential Solution: One possible solution could be to ...

Trouble with AJAX GET request functionality

I am new to AJAX and attempting to make my first AJAX call. Here is the code I have so far: $.get( "validate.php", { 'userinput':'x'}, function(response) { if( response.status ) alert( "Matches found" ); else alert( "No matches ...

Transferring Live Information Between Two Controllers

How can I transfer the 'header' and 'content' from a controller's $scope element (specifically the 'header' and 'content') to another page that is redirected to upon clicking a button? The current setup involve ...

Having trouble grasping this concept in Typescript? Simply use `{onNext}` to call `this._subscribe` method

After reading an article about observables, I came across some code that puzzled me. I am struggling to comprehend the following lines -> return this._subscribe({ onNext: onNext, onError: onError || (() => {}), ...

"Concealing specific routes in Vue Router depending on a certain condition - what's the

I need to determine which routes to hide based on a condition that evaluates to true or false. I have a collection of routes, such as: - Products - Clients For instance, if a user logs in but does not have the permission to edit products, then the updated ...

What is the best way to retrieve multiple elements by class and change their innerHTML?

Encountering an issue with calling multiple elements of the same class using .innerhtml. Here is the URL I am dealing with: When running the following code in Chrome console, this is the output: document.getElementsByClassName('a-size-small a-color- ...

How can we stop every tab pane in (bootstrap five) from sharing the same scroll position? Each tab is currently synchronized with the scroll position of the others

In Bootstrap 5, the scroll position remains the same when switching between tabs in the tab pane. Whether moving from tab #1 to tab #2, both tabs are at the identical scroll position, failing to preserve each tab's specific location. <div class=&qu ...

Determine the percentage using jQuery by considering various factors

I am facing an issue with the following code snippet: <script type="application/javascript"> $(document).ready(function () { $("#market_value").on("change paste keyup", function() { var market_value = par ...

Change glb files to draco glb in the frontend

Can we encode and transform glb files into draco glb format using only frontend technologies (client side)? ...

Navigating additional information in D3 Node Link Force diagram

Recently delving into the world of D3, I have been pleasantly surprised by its capabilities and decided to experiment with the Directional Force Layout. My Objective Initially, I successfully created a json object using a for loop to prepare my items for ...