I\'d like to execute JavaScript code from within a C# assembly and have the results of the JavaScript code returned to the calling C# code.
It\'s easier to define things
You can run your JSUnit from inside Nant using the JSUnit server, it's written in java and there is not a Nant task but you can run it from the command prompt, the results are logged as XML and you can them integrate them with your build report process. This won't be part of your Nunit result but an extra report. We fail the build if any of those test fails. We are doing exactly that using CC.Net.
You can use the Microsoft Javascript engine for evaluating JavaScript code from C#
Update: This is obsolete as of VS 2008
I don't know of any .NET specific way of doing this right now... Well, there's still JScript.NET, but that probably won't be compatible with whatever JS you need to execute :)
Obviously the future would be the .NET JScript implementation for the DLR which is coming... someday (hopefully).
So that probably leaves running the old ActiveX JScript engine, which is certainly possible to do so from .NET (I've done it in the past, though it's a bit on the ugly side!).
The code should be pretty self explanitory, so I'll just post that.
<add assembly="Microsoft.Vsa, Version=8.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/></assemblies>
using Microsoft.JScript;
public class MyClass {
public static Microsoft.JScript.Vsa.VsaEngine Engine = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
public static object EvaluateScript(string script)
{
object Result = null;
try
{
Result = Microsoft.JScript.Eval.JScriptEvaluate(JScript, Engine);
}
catch (Exception ex)
{
return ex.Message;
}
return Result;
}
public void MyMethod() {
string myscript = ...;
object myresult = EvaluateScript(myscript);
}
}
If you're not executing the code in the context of a browser, why do the tests need to be written in Javascript? It's hard to understand the bigger picture of what you're trying to accomplish here.
Could it be simpler to use JSUnit to write your tests, and then use a WatiN test wrapper to run them through C#, passing or failing based on the JSUnit results?
It is indeed an extra step though.
I believe I read somewhere that an upcoming version of either MBUnit or WatiN will have the functionality built in to process JSUnit test fixtures. If only I could remember where I read that...