I'm trying to 'augment' JavaScript by using WebBrowser.ObjectForScripting
. A piece of 'augmented' JavaScript has a function that takes an object, does something, and calls a callback that is provided on that object. I also want to fail fast and throw an exception if a callback is not a function, in other words, I'd write something like this (this is a very simple example, a real function validation would be probably include that it has apply
and call
):
[ComVisible(true)]
public class MyScriptingObject
{
public void Foo(dynamic obj)
{
Type objType = obj.GetType();
var toStringRes = objType.InvokeMember(
"toString",
System.Reflection.BindingFlags.InvokeMethod,
null,
obj,
null);
if (!toStringRes.StartsWith("function"))
{
throw new Error("`data.callback` must be a function");
}
//do something useful
obj.callback("some data");
}
}
A call in the JavaScript world would look like:
window
.external
.Foo(
{
callback: function (data) {
alert('That is what we have got from C# ' + data);
}
});
How can I unit test method Foo()
? Which test data do I provide?
Ultimately, I want to know whether obj.callback()
has been called. However, in order to get to the stage where it is executed we need to pass the validation first.
And the problem is to pass data in such a way that obj.callback
is both a method and also has toString()
and possibly apply()
.