Ways to simulate a variable imported in the module being tested without it being a function parameter can be achieved by using describe.each and changing the mock value for each test

I have a requirement to test a function within my TypeScript module.

module-to-test.ts

import { config } from './app-config';

export const isSomethingWhatINeedSelector = createSelector(
    firstDependencySelector,
    secondDependencySelector,
    (first, second) => config.key && (first || !second)
);

Instead of writing multiple tests for this scenario, I am looking into utilizing the describe.each([[],[],[]]) feature to streamline the testing process.

I specifically need to change the value of config.key dynamically for each iteration when using describe.each. When attempting to mock the configuration file like this at the beginning of the test-file:

jest.mock('./app-config', () => ({
    config: {
        key : false,
    },
}));

it affects the entire file and all its tests. My goal is to create mocks inside individual "test/it" functions to allow for dynamic changes in the key value.

Currently, the following code is not behaving as expected:

describe.each([
    [
        'should be ....',
        true, false
    ],
    [
        'should be ....',
        false, true
    ],
    /* and so forth... [], [], [] ... with only two parameters required for the question*/
])('Functionality of ...', (
    testTitle = '',
    mockStatusOfConfigKey,
    expected,
) => {
    const state = ... /* initial */

    beforeEach(() => {
        jest.resetModules();
        /*....configure the state*/
    }); 

    it(testTitle, () => {
        jest.mock('./app-config', () => ({ /*...or doMock(), which does not work as intended*/
           config: {
              key : mockStatusOfConfigKey,
           },
        }));
        expect(isSomethingWhatINeedSelector(state)).toBe(expected);
    });
});

Any suggestions on how to make mocks dynamically changeable within test functions?

config.key can only be true or false

Answer №1

Two key ideas explored in Exploring ES6 (which also hold true for TypeScript Modules):

In ES6, imported values are dynamic read-only references to exported data.

Furthermore,

Although you can't directly modify the imported values, you have the ability to alter the referenced objects themselves.


app-config provides the export of config, an object instance.

While reassigning config directly is not possible, adjustments to the underlying object it points to can be made.

Any module importing config will receive a real-time glimpse of the object and automatically reflect any changes within the object:

import { config } from './app-config';

...

  test(itTitle, () => {
    config.key = updatedConfigValue; // making changes to the config object
    expect(isNecessaryFunction(state)).toBe(expectedOutcome); // RESULT
  });
});

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

Utilize only certain JSON properties within JavaScript

I have access to an array of JSON objects. [ { Id: "1", StartNo: "1", ChipNo: "0", CategoryId: "0", Wave: "0", Club: "", FirstName: "Lotta", LastName: "Svenström", FullName: "Lotta Svenström", ZipCode: "24231" }, {...} ] My goal is to create a new data ...

The styled-components seem to be having trouble injecting the necessary CSS to handle all the various props

I am curious to understand the potential reasons for styled-components not injecting all the necessary CSS into a page's header. In an existing project, I have defined a simple button like this: const Button = styled.button` background-color: ...

Tips for creating a drawing grid with a table

I am currently working on a project where I need to create a canvas-like table with around 10,000 cells. The goal is to allow users to draw on this canvas by moving their mouse over it while holding down specific keys (e.g. ctrl for blue, shift for red). ...

Is there a way to update the value of a variable with the help of a checkbox?

When I check the checkbox, the specOrder const gets updated as expected. However, I am struggling to figure out how to remove the value when the checkbox is unchecked. Below is the code I have been working on: const SpecialtyBurgers = () => { cons ...

Why Mixin Class inference is not supported in Typescript

I encountered an issue in my code: The error message 'Property 'debug' does not exist on type 'HardToDebugUser'.' was displayed. It seems like Typescript failed to infer the mixin class correctly. Can you please explain this t ...

What is the process for discovering the kinds of models that can be generated with a Prisma client?

Ensuring data type correctness when creating a Prisma model named 'bid' is crucial. With auto-generated prisma types available, understanding the naming convention and selecting the appropriate type can be confusing. The bid schema looks like th ...

Checking the content of a textfield in React Material UI based on the user input

Hello! I am seeking a solution to trigger an error message whenever the value entered in the first text field is not equal to "28.71", otherwise display a correct message. Here is my current code: class Main extends React.PureComponent { render() { ...

Removing a specific row in a database table and sending a boolean indicator to an API, all while keeping the original object intact

I'm currently working on a spa project using AngularJS and integrating an api with mvvm in C#. One issue I am facing is that when I click the delete button, it deletes the line but I only want to change a boolean flag to true on the server side while ...

What is the process of choosing a language (English/French) within a pop-up?

<body style="text-align:center"> <h2>Popup</h2> <div class="popup" onclick="myFunction()">Interact with me to show/hide the popup! <span class="popuptext" id="myPopup">A Simple Popup!</span> </div> <script& ...

Transfer the selected user content from one canvas to another

After successfully implementing a simple selection area on canvasA, I encountered an issue with copying the area to canvasB. The user is supposed to select an area and then see that selection appear on another canvas once they finish making the selection b ...

What is the best way to eliminate an item from an array in JavaScript or AngularJS?

I'm attempting to eliminate objects from an array and retrieve the resulting array. I've been using a remove function, but it's not functioning as expected. Here is the input I'm working with: The goal is to remove all values in the ar ...

Listen for the load event during an AJAX request without using jQuery's add

I have four HTML files and four corresponding JavaScript files. Each JavaScript file is externally loaded by its respective HTML file. Specifically, index.html loads javascript.js, 1.html loads javascript1.js, 2.html loads javascript2.js, and 3.html loads ...

How can I disable auto-fill for password input fields? Setting autocomplete="off" doesn't seem to be working

Hey there, I'm having some trouble with the autocomplete feature in Google Chrome. Can anyone suggest an alternative way to disable autocomplete for password fields? By the way, my project is using Vue.js. ...

AngularJS Accordion Component: A Handy Tool for Organ

I have been trying to implement an Accordion in my angular project by sending HTML structure from a controller. However, despite following the documentation closely, the Accordion is not displaying as expected. Here is a snippet of the code I am using: v ...

Is there a way to access the current $sce from a controller?

One way to access the current $scope outside of a controller is by using the following code: var $scope = angular.element('[ng-controller=ProductCtrl]').scope(); Is there a way to retrieve the $sce of the current controller? ...

Axios: Exception handling does not involve entering the catch method

Implementing a function to adjust a contract name involves making an axios request to the backend API using a specific ID. Upon each execution, a sweetalert prompt is displayed. axios({ url: '/api/contract/' + id, method: 'put ...

Angular JS Sorting Wordpress Plugin allows users to easily organize and sort content

Seeking some assistance here, any help would be greatly appreciated. Currently using a Wordpress Angular JS plugin that is causing some unusual alphabetical sorting. This snippet of code showcases the taxonomy: <!-- for taxonomy --> <div ng-if ...

Change a reactive variable based on an event

I am currently working on a file upload feature in my application. Template.uploadFile.events({ 'change .set-file': function ( event, template ) { var file = event.currentTarget.files[0]; [...] } }); My goal is to read each row fro ...

Tips on how to highlight a clicked list item:

I'm currently attempting to access the key={1} Element within my li. My goal is to set the activeItem in State in order to compare it with the clicked item later on. If they are equivalent, I want to apply an active class to that specific element. How ...

Webpage Text Animation

This is the visual representation of my webpage: https://i.stack.imgur.com/tYq34.png I am seeking to implement a uniform animation effect for the text "Carlos Qiano" and "Lorem Ipsum", similar to the link below: https://i.stack.imgur.com/XVnBS.jpg Note: ...