I posted last week about testing JavaScript through NUnit with JSUnit. While this worked, it was a little slower to run tests than I really wanted. It was also slower (for me) to write the tests since I had to leave the comfort of NUnit and .NET for JSUnit and JavaScript.
I'm continuing to look at the problem of JS testing for ASP.NET. I evaluated YUI Test, Yahoo's JS unit test library. YUI Test actually looks very good, but I really wanted to keep things integrated with my current build and test process, even if it isn't the best solution; you don't know unless you try.
This time I'm only using NUnit and WatiN for my JavaScript tests. Since WatiN now has the ability to evaluate JavaScript and return the results, I'm using this to run the JavaScript function under test and then using an NUnit assertion for validation.
I create each test using regular NUnit syntax, and then wrap the JavaScript function call with a C# method which passes the arguments off to the JS function to test.
[Test]
public void ShouldValidateDiscover()
{
Assert.IsTrue(ValidateCreditCard("6011648040903965", "discover"));
}
private bool ValidateCreditCard(string cc, string ccType)
string testJs = string.Format("var cc = new CreditCardValidator(); cc.isValidCreditCardNumber('{0}', '{1}');", cc, ccType);
return EvalToBool(testJs);
The EvalToBool method just calls the WatiN eval method which accepts JavaScript as a parameter, and then converts the JS string result to a .NET boolean.
protected bool EvalToBool(string js)
string result = ie.Eval(js);
return bool.Parse(result);
The overall process is:
The test setup is very simple, and it runs fast for this type of test. On my PC it was taking 1.7 seconds to setup the test fixture, and then .2 seconds to run each test. The nice thing is that the errors are generally obvious and easy to diagnose since they are native NUnit tests. Its also nice to have multiple NUnit test entries in the runner instead of one monolithic JavaScript test function which encapsulated all my JS tests that run in JSUnit.
The tests can get ugly if a JavaScript exception is thrown, in that case you get a generic COM exception returned from WatiN rather than a nice error message. The is one area where a JSUnit or YUI test are naturally better at.
This makes me wonder if WatiN couldn't be extended to return better error information from JavaScript, and whether the use of a dynamic .NET language along with NUnit couldn't make for a nice testing experience.
Powered by: newtelligence dasBlog 2.1.8102.813
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2010, Shawn Neal
E-mail