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

Is there a Wordpress floating bar similar to the one seen on 9gag?

After browsing through some posts on stackoverflow, I noticed that my website is not responding as expected. You can check out my site here: To troubleshoot, you can examine the source code and utilize Firebug to inspect the css and javascript being used ...

Automatically populate form fields with data from the clicked row in the HTML table when using JSP

Attempting to populate form fields using jQuery or JavaScript with row elements selected by clicking on the row. Tried a solution from Stack Overflow that didn't work as expected. I'm new to this, so please bear with me. (http://jsbin.com/rotuni/ ...

Dynamically load scripts in angularJs

Having multiple libraries and dependencies in my angularjs application is posing a challenge as I want to load them all using just one script, given that three apps are utilizing these dependencies. Currently, I have this custom script: var initDependenci ...

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

Chaining Assignments in TypeScript

let a: { m?: string }; let b = a = {}; b.m = ''; // Property 'm' does not exist on type '{}'. let a: { m?: string } = {}; let b = a; b.m = ''; // It's OK Link to TypeScript Playground What occurs ...

Implementing a change event upon setting a value to an input element using JavaScript

My plan is to develop a Chrome extension that can automatically fill passwords. The code for this functionality looks like the following: //get the account document.querySelector("input[type=text]").addEventListener('input', () => { ...

Is the detection change triggered when default TS/JS Data types methods are called within an HTML template?

I'm currently updating an application where developers originally included function calls directly in the HTML templating, like this: <span>{{'getX()'}}</span> This resulted in the getX method being called after each change dete ...

Styling with CSS: Using a Base64 Encoded Image in the Background URL

Can a Base64 encoded image be loaded as a background image URL without exposing the actual encoded string in the page source? For example, if a Node API is used to GET request at "/image", it returns the serialized Base64 data. res.json("da ...

What is the reason for JSON.parse throwing errors on the same strings that eval does not?

Imagine having something like this: var a = '["\t"]' When you use: eval('var result = ' + a) Everything runs smoothly. However, if you try: var result = JSON.parse(a) You'll encounter an error: Unexpected token. The s ...

When using Mongoose paginate, there is always one missing document

I currently have a database with 6 documents and the following route: router.get('', async (req, res) => { const search = req.query.search !=null ? req.query.search : ""; const page = req.query.page !=null ? req.query.page : 1; const limit = ...

Issue with font-size changes using css variables in Angular not updating in browser for specific fields

Utilizing CSS variables, I have implemented a feature that allows users to adjust the font size to small, medium, or large. While this functionality works correctly for most fields, there are certain instances where the value is applied but not displayed. ...

Guide on implementing a live media stream using JavaScript

I am looking to set up a live audio stream from one device to a node server, which can then distribute that live feed to multiple front ends. After thorough research, I have hit a roadblock and hope someone out there can provide guidance. I have successf ...

Adjust the Appearance of Highcharts Legend Post-Rendering

After a Highchart is rendered, is it possible to modify the display settings without redrawing the chart? For instance, I would like to relocate the legend box from the right to the bottom upon screen resize, as illustrated in this image: --Example Pictur ...

Angular UI Bootstrap Typeahead - Apply a class when the element is added to the document body

In my current project, I am utilizing angular bootstrap typeahead with multiple instances. Some of these instances are directly appended to the body using the "typeahead-append-to-body" option. Now, I have a specific instance where I need to customize the ...

Encountering a 404 error with Next.js 13 dynamic routing

Whenever I click on an item, it redirects to the dynamic route "http://localhost:3000/products/{id}" but instead of displaying the data, I get an error. Here is my file structure: app components Product.js pages Products [id].js layou ...

Using special symbols in HTML5 data attributes

Is it feasible to locate all DOM elements using jQuery with wildcard characters in the attribute name? Take into consideration the following HTML code: <input id="val1" type="text" data-validate-required data-validate-minlength ...

JavaScript code that displays values that are not equal

Here is a code snippet that checks whether two arrays of objects are equal or not. How can we enhance this code to log which answer is not matching? The structure of the arrays: arrayA represents user answered questions, while arrayB contains correct answ ...

Unable to retrieve device UUID using capacitor/device on Android

I'm currently attempting to obtain the UUID of my devices so that I can send targeted notifications via Firebase. My front end and back end are connected, enabling the back end to send notifications to the front end using Firebase. However, all I am a ...

"Creating a cohesive design: Using CSS to ensure the navigation background complements

I am working on a project with a horizontal navbar that I want to stay fixed while scrolling. The main window has different colored divs as you scroll down, and I would like the navbar to match the image of the main div while scrolling, creating a looping ...

Test your knowledge of Javascript with this innerHtml quiz and see

How can I display the output of a score from a three button radio button quiz without using an alert popup? I want the output to be displayed within a modal for a cleaner look. I tried using InnerHTML but now there is no output when the button is clicked. ...