Checking for Broken Links

Applies to TestComplete 15.63, last modified on April 23, 2024

TestComplete provides scripting access to web page elements as well as to their attributes, methods and events. So, you can do more than just perform functional testing of a web page. With TestComplete, you can check different characteristics of a web page and its elements. This lets you easily check the page elements and determine whether the web page matches the quality standards adopted in your organization.

It is obvious that you want to make sure that your tested web page does not contain broken links. To perform a check for broken links, you can either use a web accessibility checkpoint, or write script code. By writing script code you can create a more specific checking procedure (for instance, you can verify only specific links). However, using a checkpoint you can quickly and easily perform typical checks.

You can perform a check both from scripts and from keyword tests.

Checking for Mailto Links from Scripts

To perform checking from a script, you can write special script code or use the Web Accessibility Checkpoint dialog.

Using the Web Accessibility Checkpoint Dialog

You can create a web accessibility checkpoint during test recording or at design time:

  • To create a checkpoint during the test recording, click Add Check on the Recording toolbar. Click Web page in the resulting Checkpoint wizard and then click Verify web page contents.

  • To create a new checkpoint at design time, on the Code Editor toolbar, click Add Checkpoint via Wizard and then click Web page.

In the wizard:

  • Select the web page you want to check and click Accessibility.

  • To specify that TestComplete should check for broken links, select the Check link accessibility check box.

  • Press OK. TestComplete will generate and display the code that you can then insert into your script units.

Note that instead of creating a new checkpoint, you can also modify the Check link accessibility property of an existing Web Accessibility project element and then use this element to perform the check.

For more information on creating and using web accessibility checkpoints, see Web Accessibility Checkpoints.

Using Script Code

The code snippet below checks the accessibility of all A elements on the tested web page.

The Test routine uses the contentDocument.links property to obtain the collection of all A elements. The VerifyWebObject routine uses the aqHTTP.CreateGetRequest method to create a request object, and the aqHttpRequest.Send method to send a request to a server and get a response. It uses the aqHttpResponse.StatusCode property to check whether the request was successful.

JavaScript

function Test()
{

  URL = "https://www.smartbear.com"
  Browsers.Item(btIExplorer).Run(URL);
  let page = Sys.Browser("*").Page("*");

  let expectedObjectData = "";

  // Obtains the links
  let links = page.contentDocument.links;
  let linksCount = links.length;

  if (linksCount > 0)
  {
    // Searches for broken links
    for (let i = 0; i < linksCount; i++)
    {
      let link = links.item(i);
      let URL = link.href;
      Log.AppendFolder(URL);
      Log.Message("The " + URL + " verification results: " + VerifyWebObject(URL, expectedObjectData));
      Log.PopLogFolder();
    }
  }

}


// Checks whether the specified URL is valid
function VerifyWebObject(link, expectedObjectData)
{
  let httpObj = aqHttp.CreateGetRequest(link);
  try
  {
    let httpObjResult = httpObj.Send();
    if (httpObjResult != null)
    {
      switch (httpObjResult.StatusCode)
      {
        case 200:
        case 302:

        if (httpObjResult.Text != expectedObjectData)
        {
          Log.Message("The " + link + " link is valid", httpObjResult.Text);
          return false;
        }

      break;
      default:
        Log.Message("The " + link + " link was not found, the returned status: " + httpObjResult.StatusCode, httpObjResult.Text);
        return false;

      }
      return true;
    }

  }
  catch(e)
  {
    Log.Warning(e.message);
    return false;

  }
}

JScript

function Test()
{

  URL = "https://www.smartbear.com"
  Browsers.Item(btIExplorer).Run(URL);
  var page = Sys.Browser("*").Page("*");

  var expectedObjectData = "";

  // Obtains the links
  var links = page.contentDocument.links;
  var linksCount = links.length;

  if (linksCount > 0)
  {
    // Searches for broken links
    for (var i = 0; i < linksCount; i++)
    {
      var link = links.item(i);
      var URL = link.href;
      Log.AppendFolder(URL);
      Log.Message("The " + URL + " verification results: " + VerifyWebObject(URL, expectedObjectData));
      Log.PopLogFolder();
    }
  }

}


// Checks whether the specified URL is valid
function VerifyWebObject(link, expectedObjectData)
{
  var httpObj = aqHttp.CreateGetRequest(link);
  try
  {
    var httpObjResult = httpObj.Send();
    if (httpObjResult != null)
    {
      switch (httpObjResult.StatusCode)
      {
        case 200:
        case 302:

        if (httpObjResult.Text != expectedObjectData)
        {
          Log.Message("The " + link + " link is valid", httpObjResult.Text);
          return false;
        }

      break;
      default:
        Log.Message("The " + link + " link was not found, the returned status: " + httpObjResult.StatusCode, httpObjResult.Text);
        return false;

      }
      return true;
    }

  }
  catch(e)
  {
    Log.Warning(e.description);
    return false;

  }
}

Python

def Test():
  URL = "https://www.smartbear.com";
  Browsers.Item[btIExplorer].Run(URL);
  page = Sys.Browser("*").Page("*"); 

  expectedObjectData = "";

  # Obtains the links
  links = page.contentDocument.links;
  linksCount = links.length;

  if (linksCount > 0):
    # Searches for broken links
    for i in range (0, linksCount-1):
      link = links.item(i);
      URL = link.href;
      Log.AppendFolder(URL);
      Log.Message("The " + URL + " verification results: " + aqConvert.VarToStr(VerifyWebObject(URL, expectedObjectData)));
      Log.PopLogFolder();

# Checks whether the specified URL is valid
def VerifyWebObject(link, expectedObjectData):
  httpObj = aqHttp.CreateGetRequest(link)
  try:
    httpObjResult = httpObj.Send()
    if httpObjResult != None:
      if (httpObjResult.StatusCode == 200 or httpObjResult.StatusCode == 302):
        if (httpObjResult.Text != expectedObjectData):
          Log.Message("The " + link + " link is valid", httpObjResult.Text)
          return False;
      else:
        Log.Message("The " + link + " link was not found, the returned status: " + aqConvert.VarToStr(httpObjResult.StatusCode), httpObjResult.Text)
        return False
    else:
      return False
  except Exception as e:
    Log.Warning(str(e))
    return False

  return True;

VBScript

Sub Test

  Dim page, expectedObjectData, links, linksCount, link, URL, i

  URL = "https://www.smartbear.com"
  Browsers.Item(btIExplorer).Run(URL)
  Set page = Sys.Browser("*").Page("*")

  expectedObjectData = ""

  ' Obtains the links
  Set links = page.contentDocument.links
  linksCount = links.length

  If linksCount > 0 Then

  ' Searches for broken links
  For i = 0 To linksCount - 1

    Set link = links.item(i)

    URL = link.href
    Log.AppendFolder(URL)
    Log.Message("The " & URL & " verification results: " & VerifyWebObject(URL, expectedObjectData))
    Log.PopLogFolder()

  Next
  End If

End Sub


' Checks whether the specified URL is valid
Function VerifyWebObject(link, expectedObjectData)
  Err.Clear
  Dim httpObj

  Set httpObj = aqHttp.CreateGetRequest(link)
  On Error Resume Next
    Dim httpObjResult
    Set httpObjResult = httpObj.Send
    If Not httpObjResult = Empty Then
      Select Case httpObjResult.StatusCode

        Case 200
          If (httpObjResult.Text <> expectedObjectData) Then
            Call Log.Message("The " & link & " link is valid", httpObjResult.Text)
            VerifyWebObject = False
            Exit Function
          Else
            VerifyWebObject = True
          End If

        Case 302
          If (httpObjResult.Text <> expectedObjectData) Then
            Call Log.Message("The " & link & " link is valid", httpObjResult.Text)
            VerifyWebObject = False
            Exit Function
          Else
            VerifyWebObject = True
          End If

        Case Else
          Call Log.Message("The " & link & " link was not found," & " the returned status: " & httpObjResult.StatusCode, httpObjResult.Text)
          VerifyWebObject = False
      End Select

    Else
      VerifyWebObject = False
    End If

  If Err.Number <> 0 Then

    Log.Warning Err.Description
    VerifyWebObject = False
  End If

End Function

DelphiScript

// Forward declaration
function VerifyWebObject(link, expectedObjectData); forward;

procedure Test();
var page, expectedObjectData, links, linksCount, i, URL, link;
begin

  URL := 'https://www.smartbear.com';
  Browsers.Item[btIExplorer].Run(URL);
  page := Sys.Browser('*').Page('*');

  expectedObjectData := '';

  // Obtains the links
  links := page.contentDocument.links;
  linksCount := links.length;

  if linksCount > 0 then
  begin

    // Searches for broken links
    for i := 0 to linksCount - 1 do
    begin
      link := links.item(i);

      URL := link.href;
      Log.AppendFolder(URL);
      Log.Message('The ' + URL + ' verification results: ' + aqConvert.VarToStr(VerifyWebObject(URL, expectedObjectData)));
      Log.PopLogFolder();

    end;
  end;

end;


// Checks whether the specified URL is valid
function VerifyWebObject(link, expectedObjectData);
var httpObj, httpObjResult;
begin
  httpObj := aqHttp.CreateGetRequest(link);
  try
  begin
    httpObjResult := httpObj.Send();
    if httpObjResult <> nil then
    begin
      case httpObjResult.StatusCode of

        200:
          if httpObjResult.Text <> expectedObjectData then
          begin
            Log.Message('The ' + link + ' link is valid', httpObjResult.Text);
            result := false;
            exit;
          end;

        302:
          if httpObjResult.Text <> expectedObjectData then
          begin
            Log.Message('The ' + link + ' link is valid', httpObjResult.Text);
            result := false;
            exit;
          end;

        else
        begin
          Log.Message('The ' + link + ' link was not found, the returned status: ' + aqConvert.VarToStr(httpObjResult.StatusCode), httpObjResult.Text);
          result := false;
          exit;
        end;

      end;

    result := true;
    end
    else
      result := false;
  end;

  except
  begin
    Log.Warning(ExceptionMessage);
    result := false;
  end;

  end;

end;

C++Script, C#Script

function Test()
{

  URL = "https://www.smartbear.com"
  Browsers["Item"](btIExplorer)["Run"](URL);
  var page = Sys["Browser"]("*")["Page"]("*");

  var expectedObjectData = "";

  // Obtains the links
  var links = page["contentDocument"]["links"];
  var linksCount = links["length"];

  if (linksCount > 0)
  {
    // Searches for broken links
    for (var i = 0; i < linksCount; i++)
    {
      var link = links["item"](i);
      var URL = link["href"];
      Log["AppendFolder"](URL);
      Log["Message"]("The " + URL + " verification results: " + VerifyWebObject(URL, expectedObjectData));
      Log["PopLogFolder"]();
    }
  }

}


// Checks whether the specified URL is valid
function VerifyWebObject(link, expectedObjectData)
{
  var httpObj = aqHttp["CreateGetRequest"](link);
  try
  {
    var httpObjResult = httpObj["Send"]();
    if (httpObjResult != null)
    {
      switch (httpObjResult["StatusCode"])
      {
        case 200:
        case 302:

        if (httpObjResult["Text"] != expectedObjectData)
        {
          Log.Message("The " + link + " link is valid", httpObjResult["Text"]);
          return false;
        }

      break;
      default:
        Log["Message"]("The " + link + " link was not found, the returned status: " + httpObjResult["StatusCode"], httpObjResult["Text"]);
        return false;

      }
      return true;
    }

  }
  catch(e)
  {
    Log["Warning"](e["description"]);
    return false;

  }
}

Checking for Mailto Links from Keyword Tests

To search for broken links on a web page from keyword tests, you can use the Web Accessibility Checkpoint operation or call the script routine described in the previous section.

To add the Web Accessibility Checkpoint operation to your keyword test, drag the operation from the Operations list to the test area in the Keyword Test editor. In the ensuing Checkpoint dialog, specify the tested web page, the name of the Web Accessibility project element that will be used for the verification and in the Options list select the Check link accessibility check box.

To call the described script routine from a keyword test, use the Run Script Routine operation. Prepare the script code and then append the operation to the test. TestComplete will display the Select Test dialog where you will be able to choose this script routine.

See Also

Classic Web Testing
Web Testing - Examples

Highlight search results