Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

javascript - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...