Unable to modify the Jest mock function's behavior

The issue I am facing involves the following steps:

  1. Setting up mocks in the beforeEach function
  2. Attempting to modify certain mock behaviors in specific tests where uniqueness is required
  3. Encountering difficulty in changing the values from the initial setup in step #1

Note that this code snippet is somewhat pseudo code, so there may be some syntax errors as the exact source code is not readily available:

import Module from '../module';

...

jest.mock('../module');

describe('test suite', {

let mockFn = undefined;

beforeEach(() => {
   mockFn = jest.fn(() => 'banana');
   Module.function = mockFn;
});

test('happy test', () => {
   // This test relies on Module.function returning 'banana' to function correctly
});

test('test with issue', () => {
   let mockFn2 = jest.fn(() => 'new value instead of banana');

   Module.function = mockFn2;

   // Execute test code
   // Calls to Module.function still return 'banana'
});
}


I have attempted various approaches such as using an afterEach function that calls mockFn.mockClear(). However, I have been unable to override the original mock function. While the default mock values work for most tests, there are specific instances where I need to ensure the code reacts differently based on returned values from these functions, yet I am unable to change it from the initial mock function assigned.

Edit - Below is an example of how the function is utilized:

function() {
...

  if(Module.function().includes('somevalue'){
     // Perform certain actions
  }
  else {
     fetch(Module.function() + other stuff... )
     ...
}

};

Here is the definition of the function:

export default class Module {

   public static function() {
      // Function definition here
   }
}

Thank you.

Answer №1

After some trial and error, the solution finally clicked for me. It wasn't anything groundbreaking, just a simple realization that I had misplaced the logic for changing the mocks... after already executing the function being tested. Oops! I must have wasted a good two hours exploring various methods to reset the mocks before the truth dawned on me...

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

JavaScript Enigma: Instantiate 2 Date variables with identical values, yet they ultimately display distinct dates on the calendar

I need some help understanding something in my screenshot. Although both tmpStart and itemDate have been assigned the same numeric value, they display different calendar dates. start = 1490683782833 -> tmpStart = "Sun Mar 26 2017 16:51:55 GMT+ ...

Summing values in es6 (TypeScript) without explicitly knowing their corresponding keys

I am facing a challenge with an object that has changeable keys, which I do not want to rely on. The keys in this object are not fixed. Here is an example: interface Inf { [key: string]: number } const obj: Inf = { '2020-01-01': 4, '2 ...

What is a more efficient method for incorporating optional values into an object?

Currently, I am utilizing the optional addition feature in this way: ...(!!providerId && { providerId }), ...(!!practiceId && { practiceId }), Is there a more elegant shorthand method to replace this logic, such as: yield createRemark ...

How to emulate an iPad with iOS 14.0 using React Native?

After receiving a notification from the App Store about my React Native app crashing on an iPad with iOS 14.0, I decided to check the available emulators using the command xcrun simctl list devices. The list displayed several iPads, including: iPad Pro (9. ...

Adding a custom property to a React component

Currently, I am facing an issue while attempting to modify an MUI component. Everything works smoothly until I execute the build command, at which point it fails. I have experimented with a few variations of this, but essentially I am looking to introduce ...

Establishing the initial state in React

Can someone help me with setting the default state in React? I'm working on a project that allows files to be dropped onto a div using TypeScript and React. I want to store these files in the state but I'm struggling with initializing the default ...

Error message indicating a prop type warning occurred in an inactive component

I received a warning message for a page that I am not currently visiting (I'm on the https://example.com/this-page). Warning: Failed prop type: The prop `query` is marked as required in `OtherPage`, but its value is `undefined`. "prop-types&quo ...

Encountering Syntax Errors during Angular 6 production build

I encountered an issue with my project. Everything was running smoothly, and even when I executed the command ng build --prod, it compiled successfully and generated the dist folder in my project directory. However, after copying this folder to the htdoc ...

react native ScrollView items with uniform padding at the top and bottom

I'm currently working on a scroll component that resembles a gallery of images. My goal is to center the images based on the device height with equal padding on both the top and bottom. However, I'm facing an issue where the top padding does not ...

Omit functions from category

This question reminds me of another question I came across, but it's not quite the same and I'm still struggling to figure it out. Basically, I need to duplicate a data structure but remove all the methods from it. interface XYZ { x: number; ...

Tips on removing authentication token when logging out in react native

Working with the Django Rest Framework and React Native for the front-end, I am currently facing an issue where the authentication token persists even after a user logs out from the front-end. This is evident as the token still shows in the Django admin pa ...

Incorporate a Custom Icon into NbSelect

I am currently utilizing Nebular in a project, where multiple dropdowns are being used as shown below: <nb-select fullWidth placeholder="Office" formControlName="office"> <nb-option value="Office_A"&bt;Office A</n ...

Having trouble changing the query string in the URL with Angular 4?

My search form includes various filters such as text inputs, checkboxes, and radio buttons. Whenever the user interacts with these filters, the query string in the URL needs to be updated. Consider the following scenario: http://example.com/search?myFilt ...

Utilizing the 'create' function in sqlite each time I need to run a query

I've been diving into SQLite within the Ionic framework and have pieced together some code based on examples I've encountered. import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-a ...

The validation for decimal numbers fails to function when considering the length

I've been struggling to come up with a regular expression for validating decimal numbers of a specific length. So far, I've tried using pattern="[0-9]){1,2}(\.){1}([0-9]){2}", but this only works for numbers like 12.12. What I'm aimin ...

Access denied: Unable to rename directory '/usr/local/lib/node_modules/expo-cli' due to permission restrictions

After encountering an error that appeared to be related to permissions, I spent some time troubleshooting and finally found a solution. I wanted to share it here in case it can help others facing the same issue. If anyone has alternative solutions, please ...

The specified object '[object Object]' is not compatible with NgFor, which only supports binding to iterable data types like Arrays

I have some code that is attempting to access objects within objects in a template. <table class="table table-striped"> <tr *ngFor="let response of response"> <td><b>ID</b><br>{{ response.us ...

The Angular Router is continuing to show the HomeComponent upon navigation, rather than just displaying the ChildComponent

Lately, I've been diving into Angular and attempting to create a github search application using the github api. However, I've encountered some roadblocks with routing and data passing. My goal is for the user to land on a page like /user/userID ...

Patience is key: Techniques for waiting on service responses in Angular 2

Here is the code snippet I have been working on: canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { let isAuthenticated: boolean = false this.authServiceLocal.isAuthenticated().then(response => isAuthenticated = r ...

React Native is experiencing sluggish responsiveness to touch events

While developing my first React Native app, I noticed that it was responding very slowly to touch events. To address this issue, I tried implementing FlatList instead of mapping and made several other changes as suggested. I suspect that the slow perform ...