Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing JavaScript code from the command line [duplicate]

As a total novice with JavaScript, I'm struggling to understand how to "load" my code so I can test it using unit tests outside of the application.

In PHP, I have an autoloader (composer) so I can just reference the class I want to interact with and it is loaded automatically, or I can use require_once to include a physical file and the classes or functions in that file are available to me.

So, one of the classes (stored in a file src/lib/App/Calculator.js) ...

App.Calculator = (function () {

    var Calculator = function (onUpdateCallback) {
        this.amountChange = 0.00;
        this.amountDue = 0.00;
        this.amountTendered = 0.00;
        this.onUpdateCallback = onUpdateCallback;
    };

    Calculator.prototype = {
        clear: function () {
            this.amountTendered = 0.00;
            this.calculate();
        },

        calculate: function () {
            if (this.amountDue > 0) {
                this.amountChange = Math.max(0, this.getAmountTendered() - this.amountDue);
            } else {
                this.amountChange = -(this.getAmountTendered() + this.amountDue);
            }

            if (typeof this.onUpdateCallback === 'function') {
                this.onUpdateCallback(this);
            }
        },

        getAmountTendered: function () {
            return Number(this.amountTendered);
        },

        getChange: function () {
            return this.amountChange;
        },

        setAmountTendered: function (amountTendered) {
            this.amountTendered = parseFloat(amountTendered);
            this.calculate();
        },

        setAmountDue: function (amountDue) {
            this.amountDue = parseFloat(amountDue);
            if (this.amountDue < 0) {
                this.negative = true;
            }
            this.calculate();
        }
    };

    return Calculator;

})();

I want to be able to create a new instance of App.Calculator and test it, outside of the application. From the command line.

Coming from PHPUnit to JS and I know I'm missing a LOT of understanding, so any pointers (opinionated or otherwise) would be appreciated.

like image 757
Richard A Quadling Avatar asked Oct 19 '25 04:10

Richard A Quadling


1 Answers

The best would be to just test your code in a browser using the F12 debug command line.

Another option if you want to do it in the actual command line is to use Node.JS. This is basically a back end application for javascript and what you can do is just paste the code into a .js file, then use the CMD command: "node [yourfile.js]" and it will run the file. Using console.log you can log to the command line.

like image 192
Paul de Koning Avatar answered Oct 21 '25 19:10

Paul de Koning