Create a unique TypeScript constant to be mocked in each Jest test

Having difficulty mocking a constant with Jest on a per test basis. Currently, my mock is "static" and cannot be customized for each test individually.

Code:

// allowList.ts
export const ALLOW_LIST = {
  '1234': true
};
// listUtil.ts
import { ALLOW_LIST } from './allowList.ts';

export const checkList = (id: string) => {
  if (ALLOW_LIST[id]) return true;
  return false;
};

Test (working):

// listUtil.test.ts
import { checkList } from './listUtil';

jest.mock('./listUtil', () => {
  return {
    '5678': true
  };
});

test('in list', () => {
  expect(checkList('5678')).toBe(true);
});
test('not in list', () => {
  expect(checkList('1234')).toBe(false);
});

Desired approach (not working):

// listUtil.test.ts
import { checkList } from './listUtil';

test('in list', () => {
  jest.mock('./listUtil', () => {
    return {
      '5678': true
    };
  });
  expect(checkList('5678')).toBe(true);
});
test('not in list', () => {
  jest.mock('./listUtil', () => {
    return {
      '9123': true
    };
  });
  expect(checkList('1234')).toBe(false);
});

Is it possible to achieve what I'm attempting? This post seems similar and successful when mocking functions, but I am facing the same challenges as the commenters in the accepted answer. It seems like the working version operates due to the hoisted mock that overwrites the real implementation, but I am unsure how to replicate that for each test.

One option could be exposing the ALLOW_LIST via a function:

// allowList.ts
const ALLOW_LIST = {
  '1234': true
};
export const getAllowList = () => ALLOW_LIST;

Wondering if this is necessary or if there are other solutions.

Answer №1

If you want to mock a module differently for each test, you can utilize the jest.doMock(moduleName, factory, options) method.

For example:

allowList.ts:

export const ALLOW_LIST = {
  '1234': true,
};

listUtil.ts:

import { ALLOW_LIST } from './allowList';
console.log('ALLOW_LIST: ', ALLOW_LIST);

export const checkList = (id: string) => {
  if (ALLOW_LIST[id]) return true;
  return false;
};

listUtil.test.ts:

describe('65712158', () => {
  beforeEach(() => {
    jest.resetModules();
  });
  it('should be in the list', () => {
    jest.doMock('./allowList', () => ({ ALLOW_LIST: { 5678: true } }));
    const { checkList } = require('./listUtil');
    expect(checkList('5678')).toBeTruthy();
  });

  it('should not be in the list', () => {
    jest.doMock('./allowList', () => ({ ALLOW_LIST: { 9123: true } }));
    const { checkList } = require('./listUtil');
    expect(checkList('1234')).toBeFalsy();
  });
});

Unit test results:

 PASS  examples/65712158/listUtil.test.ts
  65712158
    ✓ should be in the list (2517 ms)
    ✓ should not be in the list (2 ms)

  console.log
    ALLOW_LIST:  { '5678': true }

      at Object.<anonymous> (examples/65712158/listUtil.ts:2:9)

  console.log
    ALLOW_LIST:  { '9123': true }

      at Object.<anonymous> (examples/65712158/listUtil.ts:2:9)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |      100 |     100 |     100 |                   
 listUtil.ts |     100 |      100 |     100 |     100 |                   
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        5.03 s

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

Tips for executing multiple asynchronous calls simultaneously within a nested map function

I am facing a scenario where I have an object with nested arrays of objects which in turn contain another set of nested arrays. To validate these structures, I have an asynchronous function that needs to be executed concurrently while awaiting the results ...

Angular 5 does not allow function calls within decorators

I encountered an issue while building a Progressive Web App (PWA) from my Angular application. When running ng build --prod, I received the following error: ERROR in app\app.module.ts(108,64): Error during template compile of 'AppModule' Fu ...

Tips and tricks for accessing the state tree within effects in @ngrx/effects 2.x

I am currently in the process of migrating my code from version 1.x to 2.x of @ngrx/effects. Previously, in version 1.x, I was able to access the state tree directly within an effect: constructor(private updates$: StateUpdates<AppState>) {} @E ...

Design an array specifically for runtime using a union type

Imagine I have the following union type: type Browser = 'Chrome' | 'Firefox' I am looking to convert this into an array: const browsers = /* code to change Browser type into ['Chrome', 'Firefox'] The goal is to u ...

Transitioning to mui5's sx prop instead of makeStyles is generating a typescript error - none of the overloads match this call when passing an object with

I encountered an issue while converting a component to mui 5. Here is the original code snippet: const useStyles = makeStyles({ imageContainer: { display: "flex", width: "65%", float: "left", marginRight ...

JavaScript's Blob to Base64 conversion using FileReader is failing to produce any output

In my typescript application, I am utilizing the FileReader to convert a blob into a base64 image for display within the template. adaptResultToBase64(res: Blob): string { let imageToDisplay : string | ArrayBuffer | null = ''; const re ...

typescript push in react native is a crucial step to enhance performance and optimize

I've been diving into TypeScript within the realm of React Native. Oddly, when I translated a certain snippet to vanilla JavaScript, the application worked flawlessly. However, upon converting it back to TypeScript, an error message popped up stating ...

What is the importance of a subclass providing services to a superclass in Angular?

While exploring some Angular code today, I stumbled upon this interesting snippet: export class ContentFormComponent extends FormBase { ... constructor( private authService: AuthService, private apiService: ApiService, private segmentService: Segme ...

Encountering Build Issue: "NgSemanticModule is not recognized as an NgModule" persists despite inclusion of dependencies and importing into primary module

I have posted my module, component, and package file here. I am attempting to implement a click event with ngif, but I keep encountering an error. The specific error message is "ERROR in NgSemanticModule is not an NgModule". I'm unsure if this error ...

Is it possible to implement a customized pathway for the functions within an Azure function app?

Recently, I set up a new function app on Azure using Azure Functions Core Tools with Typescript as the language. The app includes a test function named MyTestFunction that responds with an HTTP response when called. This particular function is located in ...

Can you provide the syntax for a generic type parameter placed in front of a function type declaration?

While reviewing a project code recently, I came across some declarations in TypeScript that were unfamiliar to me: export interface SomeInterface<T> { <R>(paths: string[]): Observable<R>; <R>(Fn: (state: T) => R): Observable ...

I have noticed that my unit test case does not include coverage for the if statement

Here is the function I have in my TypeScript file: routeToIndividualPortal(sessionToken: string) { let redirectUrl = this.relayState; console.log("Pre-source-check Indivual URL : " + redirectUrl); let url = ""; if(redirectUrl.includes(this. ...

Updating a component in Angular 4.3.1 from within an observable callback

My Project Journey I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/&apos ...

What exactly does RouteComponentProps entail?

While exploring information on React, I came across the term RouteComponentProps. For example: import { RouteComponentProps } from 'react-router-dom'; const ~~~: React.FC<RouteComponentProps> and class BookingSiteOverview extends React.Com ...

Error in Jest while trying to find the @ionic/storage module in a react ionic app

For my Ionic React app, I am utilizing Jest to develop tests. This app was initially built using create react app. To start off, I wrote a basic test for the Login component: import React from 'react'; import { render } from '@testing-libra ...

Having trouble getting the mock module to work with mockImplementation

I have been facing a challenge in properly testing this File. Some tests require mocking the entire module, while others only need specific methods mocked. I have tried various combinations, but currently, for one specific test below, I am attempting the f ...

I'm encountering an issue with my Next.js development server at localhost:3001 where all routes are displaying a 404 not found page. What

Currently working on a Next.js dashboard app and encountering an issue where my localhost keeps redirecting me to the 404 page. This has happened before, but I can't recall how I resolved it. Here is the recurring problem: I attempted deleting the .n ...

Encountering an issue while developing a Discord bot using TypeScript

Hello, I'm currently working on creating a nick command for my discord bot in TypeScript, but I encountered an error. Here is the issue: Error: Expression expected.ts (1109) When I replace const mentionedMember = message? message.mentions.members? ...

An issue was encountered at node_modules/@fullcalendar/core/main.d.ts(1196,54), error TS1144: Expecting either '{' or ';'

When attempting to execute npm run build in my project, I encountered the following error: ERROR in node_modules/@fullcalendar/core/main.d.ts(1196,54): error TS1144: '{' or ';' expected. node_modules/@fullcalendar/core/main.d.ts(1197,34 ...

Encountering a warning message in Vue 3 Migration Build using Typescript: Error in finding export 'default' (imported as 'Vue') within the 'vue' package

I've been working on migrating my vue2 application to Vue3 using the Migration Build. I diligently followed the steps outlined in the documentation available at https://v3-migration.vuejs.org/migration-build.html, but despite that, I still keep encoun ...