Attempting to revert the imported module back to its initial/default mock configuration

When working on my test file, I utilize a folder named mocks which contains various exported functions. Most of the time, I rely on the mocks folder to perform all necessary tasks. However, there is one scenario where I need to adjust the return value to accommodate another function. Unfortunately, I am unsure how to revert back to the original/default mock.

Consider the following example:

// __mocks__/user.ts
export default someModuleFunction = () => {
  return 'default mock'
}

// user.test.ts
import {someModuleFunction} from 'user';
jest.mock('../users')

describe("TestFile", () => {

 it("should mock the return value in here", () => {
  (someModuleFunction as jest.Mock) = jest.fn().mockReturnValue(null)
  expect(someModuleFunction).toEqual(null)
 })
 
 it("should fallback to the original default mock", async() => {
   expect(someModuleFunction).toEqual('default mock')
 })
})

Answer №1

A mistake is made when assigning to someModuleFunction because ES modules are read-only. The only reason this works is because they are transpiled to CommonJS. It is not recommended to restore mocks by reassignment. A slightly better but still incorrect approach would be to import * and use spyOn on it.

This situation applies to isolated modules, where a module must be re-imported for each test:

 During testing the return value should be mocked in the following way: 
  jest.isolatedModules(() => {
    jest.doMock('user', () => /* mock it */);
    const {someModuleFunction} = require('user'); // mocked
    /* require modules that depend on this mock */
  });
 

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

React components need to refresh after fetching data from an API

I am currently working on a React application using TypeScript and integrating JSONPlaceholder for simulating API calls. I have successfully set up everything I need, but I am encountering an issue with re-rendering components that display response data fr ...

The specified 'contactId' property cannot be found within the data type of 'any[]'

I am attempting to filter an array of objects named 'notes'. However, when I attempt this, I encounter the following error: Property 'contactId' does not exist on type 'any[]'. notes: Array < any > [] = []; currentNot ...

The Angular route successfully navigated to the page, but the HTML content was not

Whenever I select the Home option in the navigation bar, it takes me to the home URL but doesn't display the HTML content. Below is my app.routing.module.ts code: import { Component, NgModule } from '@angular/core'; import { RouterModule, Ro ...

Instead of showing the data in the variable "ionic", there is a display of "[object object]"

Here is the code snippet I'm working with: this.facebook.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => { this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height( ...

The 'asObservable' property is not present on the type '() => any'.ts(2339)

Error: Property 'asObservable' does not exist on type '() => any'.ts(2339) Error: Property 'subscribe' does not exist on type 'Subscription'. Did you mean 'unsubscribe'?ts(2551) Error: Property 'sub ...

Accessing data retrieved from an API Subscribe method in Angular from an external source

Below is the Angular code block I have written: demandCurveInfo = []; ngOnInit() { this.zone.runOutsideAngular(() => { Promise.all([ import('@amcharts/amcharts4/core'), import('@amcharts/amcharts4/charts') ...

Is there a way to operate both websocket and http methods concurrently on a server in Typescript?

I have a question regarding running a websocket server with the route "ws://localhost:port" using the 'ws' library. It requires the app instance of 'express' and also features http routes such as "http://localhost:port/auth/login". I am ...

Utilizing ES6 Promises in Mongoose with Typescript to Create a Seamless Chain

When attempting to chain ES6 promises with Mongoose 4.5.4, I encountered an error in Typescript. public static signup(req: express.Request, res: express.Response) { UserModel.findOne({ email: req.body.email }).exec() .then(existingUser => { ...

Ensure that the web application is successfully logged into using MSTest, and verify that the application is fully loaded before proceeding

I've encountered an issue while using MSTest in Visual Studio 2019 with Selenium. It seems that after logging in, Selenium struggles to locate an element on the dashboard. Upon further investigation, I discovered that my login method within the OneTim ...

Making changes to a single formControl in angular6 will cause the other formControl to be updated as

I have two select menus in my user interface with the same options. When I select an option in one menu, I want the other menu to display the same option, and vice versa. Currently, I am using the valueChanges method on the first formControl to update the ...

What is the best way to send multiple parameters to @Directives or @Components in Angular using TypeScript?

I am facing some confusion after creating @Directive as SelectableDirective. Specifically, I am unclear on how to pass multiple values to the custom directive. Despite my extensive search efforts, I have been unable to find a suitable solution using Angula ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

Angular's text interpolation fails to update when a value is changed by an eventListener

I am encountering an issue with two angular apps, one acting as the parent and the other as the child within an iframe. The HTML structure is quite simple: <div class="first"> <label>{{postedMessage}}</label> </div> &l ...

Unable to find any routes that match child routes using the new Angular 2 RC1 router

ApplicationComponent import { Component } from '@angular/core'; import {Router, ROUTER_DIRECTIVES, Routes, ROUTER_PROVIDERS} from '@angular/router'; import {SchoolyearsComponent} from "./schoolyear/schoolyears.component"; @Component({ ...

Most effective method for filling in nested information

Let me start by admitting that I've delved deep into this issue, possibly missing a simpler solution along the way. If there is an obvious solution staring me in the face, I apologize! Here's the problem at hand: I'm working with a set of ...

The react decorator for maintaining type safety fails to identify the appropriate ReturnType of the supplied function

I want to enhance the redux connect feature by using it as a decorator for a specific reducer/state. Although I know that redux connect can already be used as a decorator, I am curious about why my custom implementation does not work the way I expect. Her ...

What methods can be used to validate try-catch code in JavaScript with Jest, and how can a next() call be incorporated with middleware in

Currently, I am in the process of creating an API and one of my tasks involves testing a try-catch block. My main objective is to ensure that any errors caught by the block are passed through 'next()' in Express to reach the next middleware. To ...

Need to end all Node.js instances to properly reflect the code. Any solutions for resolving this issue?

After developing an application using typescript, hapi, and nodejs, I encountered a strange issue. Whenever I save, remove, or add new code, the changes are not reflected even after running gulp build. The only way to get it working is by closing all run ...

Steps for creating a click event for text within an Ag-Grid cell

Is there a way to open a component when the user clicks on the text of a specific cell, like the Name column in this case? I've tried various Ag-Grid methods but couldn't find any that allow for a cell text click event. I know there is a method f ...

Using Typescript generics to create parameter and argument flexibility for both classes and

I'm facing an issue where I need to effectively chain multiple function calls and ensure that TypeScript verifies the correctness of their linkage. export class A<T, K> { public foo(a: A<K, T>): A<K, T> { return a; } } cons ...