What is the best way to simulate a specific file from an external package using Jest?

Currently, I am developing a project in Typescript that relies on an external package (written in JavaScript) through npm. During testing, I only want to mock one specific JS file from that package.

Is there a way to achieve this using Jest?

The package.js file includes:

  "dependencies": {
    ...
    "@company/product": "1.8.0"
    ...

Within someFile.ts:

import * as sdk from "@company/product";

I attempted to create a mock like this:

In someFile.spec.ts:

...

const prefs: IPrefs = {
  some_property: -1
};

jest.mock(
  "@company/product/sdk/api/prefs.js",
  (): { Prefs: IPrefs } => {
    return {
      Prefs: prefs
    };
  }
);

This is the original "prefs.js" file from the external package:


import ... // I can see in the failed test stack trace

export let Prefs = {
  ...
};

Despite my efforts, it does not effectively mock the file since I am still seeing the stack trace from the original "prefs.js" provided by the external package.

Answer №1

import * as lib from "@organization/service";


const mockSettings = {
  custom_setting: -1
};


jest.mock('@organization/service/lib/api/settings.js', () => ({
  Settings: mockSettings
}));

// Start testing module after setting up the mock
import { functionToTest } from './someFile';

describe('Testing someFile Module', () => {
  it('should utilize the mocked settings', () => {
    const output = functionToTest();
    expect(output).toEqual(/* expected result based on mockSettings */);
  });
});

Answer №2

  • Establish a __mocks__ folder next to the node_modules

  • Within the __mocks__ directory, mirror the structure of the package you wish to mock.

In the

__mocks__/company/product/sdk/api/prefs.js
file, create the mock implementation for your function:

export const someFunction = jest.fn(() => {
  // Add logic here;
});

Using jest.fn(), you can customize a mock function for your testing purposes.

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

Combine various canvases into a single one (for exporting purposes) with pure Javascript

I'm currently faced with a unique challenge involving the creation of around 200 canvases, each showcasing an image captured from the user's webcam as part of an experimentation process for the "photo finish" technique. My task now is to export ...

Changing the contents of a global array in JavaScript

$(document).ready(function(){ var currArray=null; var group=null; var admin=null; var equipment=null; var student=null; console.log("after get array info"); for(var i=0; i<equipment.length; i++) { console.log("equipment at index after get array info ...

Navigating the dot notation to uncover the data type of a field within an object

When working with an object type, we can access the type of one of its fields using bracket-string notation. However, why isn't it possible to use dot notation like in JavaScript? Could there be a conflict or some other reason for this limitation? I h ...

"Customize your website with sleek Rails jQuery dropdown menus for a multitude

Just dipping my toes into the world of jquery, feeling a bit lost with it (and javascript). After scouring the internet for hours, I stumbled upon a pretty straightforward method to create a dropdown menu. It does the job, but unfortunately, it only works ...

Participant joins in the game table and reacts

I am looking to set up a table where players can join and have their usernames displayed at the bottom of the screen just like in other games. How can I achieve this? export const GameStart = (props) => { const params = useParams(); const gameID = p ...

Streamlining the code

Below is the code that I am working with: $j(document).ready(function(){ $j('#uang').on({ focus: function(){ var ini = $j( this ); var theVal = accounting.unformat( ini.val() , ',' ); var ...

Encountered a cyclic dependency in MongoDB when attempting to create an index

I have a dataset structured as shown in the image below: https://i.sstatic.net/eu2ZH.png I am attempting to write a query using $near. However, when trying to create an index for this query, I encounter an error stating "cyclic dependency detected". Below ...

Error: The property 'slice' cannot be read from an undefined value

I am currently working on a prototype recipe app called Forkify, which is being developed using Javascript, NPM, Babel, and Webpack. In this project, I am utilizing a custom API. API URL : forkify-api.herokuapp.com TO SEARCH RESULT This API returns a l ...

Struggling to retrieve information from JSON using ReactJS

I am currently working with a JSON file called data.json { "link_template": "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit={num-results}&country={country-code}", "links": { "alternate": "http://www.rottentoma ...

Activating HTML 5 mode within Angular

Currently working on my first Single Page Application in AngularJS, and I've run into a roadblock with the routing. I'm attempting to enable HTML 5 like so: .config(function ($routeProvider, $locationProvider) { $locationProvider.html5Mode( ...

Having trouble getting typeahead suggestions to display in Bootstrap UI when using AngularJS?

I am having trouble getting static suggestions to display in a search textbox. I have tried following the example at this link. Below is the code I am working with: Here is my HTML code: <div> <input type="text" name="questions" id="que ...

What is the best method for coordinating the Vue mounted function with external dependencies?

Within my Vue mounted function, I am in need of both an internal value referred to as foo and an external value known as bar. Here is a snippet from myVue.js file -- //myVue.js export var myVue = new Vue({ el: '#my-vue', data: { ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

Unrecognized files located within the same directory

My main.html file located in the templates folder also contains three additional files: date.js, daterangepicker.js, and daterangepicker.css. Despite including them in the head of the HTML as shown below: <script type="text/javascript" src="date.js"> ...

Going through each file individually and addressing any issues

I have a folder with hundreds of files that I need to read. Currently, my method reads all the files at once and returns the content as an array. However, I want to optimize this process by reading one file at a time and sending it to the client before mov ...

The final thumbnail fails to appear in the visible display (react-responsive-carousel)

I am currently facing an issue with displaying a series of images using react-responsive-carousel. When the images exceed a certain size causing the thumbnail section to become scrollable, the last thumbnail is always out of view. Although I have impleme ...

Is there a way to cycle through each element within a loop and output a corresponding item from another array?

My data structure consists of an array of objects like this: arrOfObjs = [{type: "flower", egg: "something"}, {type: "flower", egg: "something2"}, {type: "notFlower", egg: "something3"}, {type: &q ...

Meteor: Display each element of a MongoDB array in its own individual list item

Note: The full code can be accessed from this link: https://github.com/Julian-Th/crowducate-platform/tree/feature/courseEditRights Currently, the items in an array are being displayed as a single list instead of separate list tags: https://i.sstatic.net ...

Mocking a React component with Jest's MockImplementation

Currently, I am in the process of testing a react component that renders another component. This secondary component makes an API call to fetch data which is then displayed on the screen. My goal is to understand how I can mock this particular component&ap ...

Do constructors in TypeScript automatically replace the value of `this` with the object returned when using `super(...)`?

I’m having some trouble grasping a concept from the documentation: According to ES2015, constructors that return an object will automatically replace the value of “this” for any instances where “super(…)” is called. The constructor code must ...