简体   繁体   中英

Test private members on javascript

I've been working on a simple project on Adobe Extend Script Toolkit and is having trouble implementing tests on private members. I have come up with a solution which is to expose the privates inside a callback to a special function. I'm not sure if this is a good pattern. I need suggestions.

Heres the pattern:

(function (global) {
    var Loader, Require, Modules;

    Require = 'Require Object';
    Modules = 'Modules object';
    Loader = {};

    global.estk = global.estk || {};
    global.estk.loader = Loader;

    // This MUST be used for testing purposes only.
    // Use this to test for private members.
    global.estk.loader.__test__ = function (callback) {
        callback.call(this, {
            Require: Require,
            Modules: Modules,
            Loader: Loader
        });
    };
}($.global));

In my test file I can then call the exposed privates like this:

(function(global) {
    #include '../estk/loader.jsxinc';

    estk.loader.__test__(function (obj) {
        $.writeln(obj.Require);
        $.writeln(obj.Modules);
        $.writeln(obj.Loader);
    });
}($.global));

As a general rule: if you need to test private data members, you need to rethink how you're doing things. You should test that given a set of inputs, the output is what you expect. These inputs should enter at the same place they enter in the public-facing API.

Unit testing should test the public interface of your code. Testing private parts tends to result in brittle tests (tests that fail when the code changes but not the results).

See this answer as well.

So, to answer your question directly: I wouldn't say that your pattern is good. You shouldn't worry about testing private functions. Test behavior, not methods. Not every method needs a test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM