New to Telerik Test Studio? Start a free 30-day trial
Handling JSON Objects
Your tests can understand JSON (JavaScript Object Notation) and can handle strongly typed objects returned from JavaScript. This might be a bit advanced for regular testers implementing test automation. However, if you are building mini-frameworks on top of Telerik Testing Framework, it is a great tool to help you get rid of having to parse complex strings returned by the InvokeScript function.
This is a basic example of how to use JSON:
C#
[TestMethod]
public void KeyValuePairs()
{
Manager.LaunchNewBrowser();
// We are using a dummy call here. The call can be to any JS method on your page
JsonObject o = ActiveBrowser.Actions.InvokeScript<JsonObject>(
"({key1:'value1', key2:'value2'})");
Assert.AreEqual<string>("value1", o["root"]["key1"]);
Assert.AreEqual<string>("value2", o["root"]["key2"]);
}In this example we define our own object in a Data Contract:
C#
[DataContract]
public class MyObject
{
[DataMember(Name = "one")]
public int One { get; set; }
[DataMember(Name = "fifteen")]
public int Fifteen { get; set; }
}
[TestMethod]
public void ReturnObject()
{
Manager.LaunchNewBrowser();
MyObject o = Actions.InvokeScript<MyObject>("({one:1, fifteen:15})");
Assert.AreEqual<int>(1, o.One);
Assert.AreEqual<int>(15, o.Fifteen);
}In this example we'll access an array returned by InvokeScript, treat it as JSON, and parse it manually for its values.
C#
var actions = Manager.Current.ActiveBrowser.Actions;
JsonObject result = actions.InvokeScript <JsonObject>("window.my_list=[1,2,3]");
JsonArray arr = (JsonArray)result["root"];
for (int i = 0; i < 3; i++)
{
double val = arr[i];
Log.WriteLine(val.ToString());
}