While this question may be older, I share similar interests and felt compelled to provide an answer. If you are working with object-oriented JavaScript and looking to test those objects, there are various tools available.
One common suggestion is to use JsTestDriver. However, JsTestDriver requires the JVM to be installed on your machine and relies on 'Slave' browsers. For unit testing JavaScript objects, I prefer using tools like WatiN, JSMock, or JsMockito.
I have personally utilized Windows Script Host for running JavaScript unit tests over the years, which offers several advantages:
- No need for a browser.
- CScript is pre-installed on Windows machines since XP.
- Runs in the background without requiring an interactive UI.
- Easy integration with build systems like CC.NET, Hudson, or TeamCity.
- Debugging support by running tests inside a debugger.
However, there are some drawbacks to consider as well:
- The machine running tests needs the ability to spawn new processes (CScript).
- Slightly slower than traditional unit tests when run individually.
Using JSTest.NET, you can create test fixtures with a structure similar to the example below:
// Sample test fixture in JSTest.NET
using JSTest;
using JSTest.ScriptLibraries;
using Xunit;
namespace JSTest.Sample
{
public class EventDispatcherTests
{
private readonly TestScript _testScript = new TestScript();
public EventDispatcherTests()
{
// Add files under test
_testScript.AppendFile(@"..\..\..\Web\Scripts\eventDispatcher.js");
// Add mock/assertion libraries
_testScript.AppendBlock(new JsHamcrestLibrary());
_testScript.AppendBlock(new JsMockitoLibrary());
// Set up common scripts
_testScript.AppendBlock(@"var dispatcher = new EventDispatcher();
var mockHandler = JsMockito.mockFunction();
var mockPredicate = JsMockito.mockFunction();
var fakeEvent = { eventType: 'CommentAdded', data: 'Sample Comment' };
");
}
[Fact]
public void ProcessEventInvokesAttachedHandler()
{
// Test implementation goes here
}
[Fact]
public void ProcessEventGracefullyHandlesPredicateException()
{
_testScript.RunTest(@"var mockPredicateAlternate = JsMockito.mockFunction();
JsMockito.when(mockPredicateAlternate)(fakeEvent).thenThrow('MyException');
dispatcher.attachListener(mockHandler, mockPredicateAlternate);
dispatcher.processEvent(fakeEvent);
JsMockito.verify(mockPredicateAlternate)(fakeEvent);
JsMockito.verifyZeroInteractions(mockHandler);
");
}
}
}
This approach simplifies JavaScript unit testing and integrates seamlessly with existing build processes.