1

I have the following (simplified) code:

function addOnclickFunction(onclickFunction) 
{
    var object = document.createElement("img");
    object.onclick = function(){eval(onclickFunction)};
    return object;
}

i.e. I am passing in a string (onclickFunction) and setting the onclick event for the object equal to whatever the string passed in was.

In terms of whether or not this approach works, then yes, it works in production.

I am however having issues unit testing this properly in QUnit.

QUnit.test("addOnclickFunction should return the an object with onClickproperty", function(assert) 
{
    var objectTest;
    assert.equal(objectTest,undefined);
    objectTest = addOnclickFunction("functionCall");
    assert.notEqual(objectTest.onclick,null);
    assert.equal(objectTest.onclick,"functionCall");
});

In this case the first 2 unit tests will pass. The last one will not as the objectTest.onclick returns

function(){
  [code]
}

Is there any way I can make it tell me what the function name is?

Martin
  • 43
  • 7
  • You can fetch the actual function object and check `func.name`. – VLAZ Oct 31 '16 at 16:20
  • What is the syntax for that? – Martin Oct 31 '16 at 16:28
  • http://stackoverflow.com/questions/2518421/jquery-find-events-handlers-registered-with-an-object this might help with getting the click all click handlers. As for the name itself if you have `var func = function myHandler() {}`, then `func.name` will return the string **"myHandler"**. So you can fetch the handlers (since there might be more than one) and check the names. – VLAZ Oct 31 '16 at 16:41
  • I am not interested in the myHandler name. I am interested in whatever is inside the { } of the function, i.e. that the string I pass in as onclickFunction appears there. – Martin Oct 31 '16 at 16:54
  • In that case, you _could_ examine the `toString` of the function but I'd sugest against it. I think that unit test will not be useful as it is too focused and it does not test something meaningful. If you want to test the _implementation_ then just write a unit tests for the specific function itself, and that it operates correctly. Then you can have a separate test to check if the _correct_ function is being added as a handler. Checking if the correct function is added and that it arbitrarily has something in it, is not that sensible. – VLAZ Oct 31 '16 at 17:02

0 Answers0