Testing an ASP.NET Web Service using JavaScript

I was teaching a technical training class on the Microsoft Redmond, WA campus last week when one of the students asked if it was possible to test an ASP.NET Web Service using JavaScript. Yes, it is possible, and quite easy. Suppose you create an ASP.NET Web Service which contains a dummy Web Method named TriMax(x,y,z) which simply returns the largest of integers x, y, and z. Listed below is the basis of JavaScript test automation. The key idea is to use an XMLHTTP object to send a request to the Web Method and grab the resulting XML response. The XMLHTTP object is normally used to send asynchronous requests to an AJAX Web application, but by setting the second parameter to "false" you can send a synchronous request. You can determine the HTTP POST data using Visual Studio by instructing the ASP.NET Web Service to run — it gives you the POST template that you can copy-paste. Very clean and easy. 
// testWebService.js
WScript.Echo("\n Starting test");
var req = new ActiveXObject("Microsoft.XMLHTTP");
req.open("POST", "http://localhost/MyService/Service.asmx", false);
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "http://tempuri.org/TriMax");
strReq = ‘<?xml version="1.0" encoding="utf-8"?>’
  + ‘<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">’
  + ‘  <soap:Body>’
  + ‘    <TriMax xmlns="http://tempuri.org/">’
  + ‘      <x>3</x>’
  + ‘      <y>7</y>’
  + ‘      <z>5</z>’
  + ‘    </TriMax>’
  + ‘  </soap:Body>’
  + ‘</soap:Envelope>’;
var response = req.responseText;
if (response.indexOf("<TriMaxResult>7</TriMaxResult>") >= 0)
WScript.Echo("\n End test"); 
This entry was posted in Software Test Automation. Bookmark the permalink.