1

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().

Mike Borozdin
  • 1,138
  • 3
  • 14
  • 32
  • Why don't you just use an actual instance of `WebBrowser` and some actual JavaScript? E.g., you can use my [`MessageLoopApartment`](http://stackoverflow.com/a/22262976/1768303) to run it under your unit-testing execution environment. – noseratio Mar 18 '15 at 23:33

0 Answers0