Imagine your tests are driven by a spreadsheet and some columns in the spreadsheet contain names of scenario functions you want to execute in your tests. How to invoke a function if its name is stored in a variable?

There are two major ways of doing this.

Method 1 (quick and dirty)

So you have something like this:

function fnLogin(userName, password)
{
	Tester.Message("User: " + userName);
	Tester.Message("Pass: " + password);
}

function fnLogout()
{
	Tester.Message("Logged out");
}

var strfn = "fnLogin";

What is next? Using the below code will not work:

strfn(); // throws error

One option is to use 'eval':

eval(strfn + "('user1', 'pwd1')");
//or
eval("fnLogout()");

Notice that you need to construct a whole string representing a function call, including parameter passing.

Method 2 (recommended)

This method requires a bit more time to setup but is more secure, faster and easier to use.

/*
 * Setup
 */

// create context object
var context = {};

// assign functions to the object
context["fnLogin"] = fnLogin;
context["fnLogout"] = fnLogout;

// this is the method performing execution of functions
function execFn(fnName, ctx /*, args */) 
{
  // get passed arguments except first two (fnName, ctx)
  var args = Array.prototype.slice.call(arguments, 2);
  // execute the function with passed parameters and return result
  return ctx[fnName].apply(ctx, args);
}


/*
 * Usage
 */

execFn(strfn, context, "user2", "pwd2");
execFn("fnLogout", context);