Are there any unit test javascript functions defined inside the function?

I would just like to ask if I can unit test the code inside the ExternalFunction inside document.ready? I tried a lot of things for a while and still could not figure out how, and I'm on my way.

$(document).ready(function () {
    var originalExternalFunction = ExternalFunction;
    ExternalFunction = function(context, param) {
        // trying to unit test the stuff in here!
    }
}

I am testing a module using JsTestDriver. A test declaration is something like TestThisTest.prototype.test_this - function () {};

Thanks in advance.

+3
source share
4 answers

ExternalFunction , (, , , ready). , .

, ExternalFunction ready ( , ). , - ready, , . , , .

. , . newExternalFunction - , .

ready, newExternalFunction :

   var newExternalFunction;
    $(document).ready(function () {
        var originalExternalFunction = ExternalFunction;
        newExternalFunction = function(context, param) {
            // trying to unit test the stuff in here!
        }
        ExternalFunction = newExternalFunction;
    }

, ready , ExternalFunction reset originalExternalFunction.

+2

- :

function newExternalFunction(context, param) {
    //etc.
}

$(document).ready(function () {
    var originalExternalFunction = ExternalFunction;
    ExternalFunction = newExternalFunction;
}

newExternalFunction.

+1

- :

ExternalFunction = function() { }
ExecuteDocumentReady(); // implement a mock on $(document).ready(fn) to store the function, and then execute it here

ExternalFunction(fakeContext, fakeParam);
assert(fakeContext.foo == 12); // or whatever you need it to do

, , javascript.

0

:

// create function to make your "extension" function
function createHookFunction(callback) {
  // return a function 
  return function(context, param) {
     var ret;
     // // trying to unit test the stuff in here!


     if (typeof callback == 'function') {
       // if you want to trap the return value from callback, 
       // ret = callback.apply(...);
       callback.apply(this, arguments);
     }
     return ret;
  };
}

// your hook now becomes:
$(document).ready(function() {
  ExternalFunction = createHookFunction(ExternalFunction);
});

// and your unit test becomes:
var funcToTest = createHookFunction();
funcToTest(testContext, testParam);

// And, you could even test that the callback itself gets called

function someTest() {
  var testContext = {}, testParam='test';
  var callbackCalled = false;
  var funcToTest = createHookFunction(function(context, param) {
    callbackCalled = (context === testContext) && (param === testParam);
  });
  return (funcToTest(testContext, testParam) == 'Expected Return') && callbackCalled;
}
0

Source: https://habr.com/ru/post/1726293/


All Articles