PhantomJS is a headless WebKit with JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. It is full web stack an optimal solution for Headless Website Testing, Screen Capture, Page Automation and Network Monitoring.
I suggest you to use this framework when you want to test some JavaScript library and don't want to use installed browser on test machine.
1.Please make sure that you already set autostart of QUnit to false.
QUnit.config.autostart = false;
2.Download PhantomJS executable file for Windows, add to your project and set "Copy to Output Directory" equals "Copy if newer".
3.Create process to run PhantomJS.exe with 2 arguments that are JavaScript file and tested page url.
var scriptPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../PhantomScript/main.js"));
var pageUrl = "file:///" + Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../QUnitExample/qunit-demo.htm")).Replace('\\', '/');
var process = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "phantomjs.exe",
Arguments = "\"" + scriptPath + "\" \"" + pageUrl + "\""
}
};
4.Start process and check the exit code of this process.
process.Start();
process.WaitForExit();
Assert.AreEqual(process.ExitCode, 0);
In JavaScript file, I use eveluateAsync for accessing context of page to run QUnit test, wait until it finish and log amount of test failed.
page.evaluateAsync(function ()
{
QUnit.done(function(response)
{
console.log('!Exit' + response.failed);
});
QUnit.start();
// If QUnit finish after 2500 ms, system will exit application with code -1.
setTimeout(function()
{
console.log('!Exit-1');
}, 2500);
});
To handle log, I use the following code to exit process with exit code.
var exitCodeName = '!Exit';
page.onConsoleMessage = function (msg)
{
if (msg.indexOf(exitCodeName) == 0)
{
var exitCode = parseInt(msg.substring(exitCodeName.length).trim(), 10);
phantom.exit(exitCode || 0);
}
};
PS. I also provide full source code (VS2012) to my SkyDrive. You can download it at the following link.
PhantomJS Test project
This project demo you how to run PhantomJS in MSTest.
PhantomJS Form project
This project is PhantomJS wrapper that is wrote in C# Windows Form. I use this to test "main.js" and "core.js" files before use it in test project.