0

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?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Ohad Yeahhh
  • 191
  • 1
  • 10
  • 1
    why are using `static`? – Tibebes. M Jan 07 '21 at 13:16
  • To complement @Tibebes.M: …and [why are you using `class`](https://stackoverflow.com/q/29893591/1048572)? – Bergi Jan 07 '21 at 13:27
  • Tibebes.M & @Bergi I don't use any framework that comes with dependency injection mechanism and I wanted to avoid spreading instances among different files. Also, I needed to have some in-memory data that could be shared across the app. Because all this functions work with the same data, I thought it would be a good practice to put it in one place and I thought that a class is an appropriate way to do it. – Ohad Yeahhh Jan 08 '21 at 01:34
  • Put it one place, yes, but a simple module or object literal would've been enough. `class`es should be used when you want to instantiate multiple objects. – Bergi Jan 08 '21 at 09:13

1 Answers1

-1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375