JSFiddle - React, Tailwind, and code Playground

by Brian Dukes

HTML

<link rel="stylesheet" href="https://github.com/jquery/qunit/raw/master/qunit/qunit.css">
<h1 id="qunit-header">QUnit Test Suite</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>

JavaScript

var obj = {
    count: 0,
    increment: function () {
        this.count += 1;
    }
};

test("can call as method", function() {    
    obj.increment();
    equal(1, obj.count, "Count incremented");
});
test("can call as standalone function", function() {   
    var increment = obj.increment;
    increment();
    equal(1, obj.count, "Count not incremented");
    
    window.count = 'global count value: ';
    increment();
    equal('global count value: 1', window.count, "Added 1 to global count variable");
});

test("can set this via call", function() {    
    var newObj = {count:50},
        increment = obj.increment;
    increment.call(newObj);
    equal(51, newObj.count, "newObj count incremented");
});
asyncTest("this changes in callback", 1, function () {
    obj.alertAfterTimeout = function () {
        setTimeout(function () {
            start();
            equal(window.count, this.count, 'this becomes global');
        }, 1);
    };
    
    obj.alertAfterTimeout();
});
asyncTest("secure this with proxy", 1, function () {
    obj.alertAfterTimeout = function () {
        var c = this.count,
            proxiedFunction = $.proxy(function () {
                start();
                equal(c, this.count, 'this does not become global');
            }, this);
        setTimeout(proxiedFunction, 1);
    };
    
    obj.alertAfterTimeout();
});
asyncTest("secure this with new variable", 1, function () {
    obj.alertAfterTimeout = function () {
        var c = this.count,
            that = this;
        setTimeout(function () {
            start();
            equal(c, that.count, 'this does not become global');
        }, 1);
    };
    
    obj.alertAfterTimeout();
});