How to initialize private property of a class for a test

I’m trying to write a test using JEST to a class I wrote with static properties that resembles the following:

class DataManager {
    static #data = null;

    static getData = () => {
        return this.#data;
    }

    static initializeData = async () => {
        await database(async (db) => {
            const data = getSomeDataFromDatabase() //just example
            this.#data = data;
        });
    }
}

Now, I want to make new implementation for my initializeData method, to returned some mocked data instead of going to the db, and then “getData” to see if I get the expected result. The problem is that my #data property is private and I don’t want to expose it to the outside world. Is there any way to do it?

Answer

No, there is no way to do that. Private fields are really private. If you want to mock them in a test, don’t use private fields. Or the other way round: if they’re private (an implementation detail), you shouldn’t mock them.

You need to either mock the entire DataManager class and its public methods, or if you want to test the DataManager itself then you’d mock the database and getSomeDataFromDatabase functions that it calls.