Coded UI - C# - ExecuteScript - count does not ret

2019-08-18 13:25发布

问题:

I am observing a strange behavior using ExecuteScript in Coded UI. When two numbers are next to each other, count does not return the correct value. I'm not sure why it's happening. Here is the code snippet:

static long nowYearQA = 2030;
static long pastYearQA = 2029;

BrowserWindow window = new BrowserWindow();
window.WaitForControlEnabled();

long countCurrentYearQA = (long)window.ExecuteScript("count = 0; if(document.body.innerHTML.toString().indexOf('" + nowYearQA.ToString().Trim() + "')  > -1){count = 1;} return count;");
long countPastYearQA = (long)window.ExecuteScript("count = 0; if(document.body.innerHTML.toString().indexOf('" + pastYearQA.ToString().Trim() + "')  > -1){count = 1;} return count;");

MessageBox.Show(countCurrentYearQA + " " + countPastYearQA);

This is for a page validation where I'm checking whether certain number presents in the Inner Text of a page. If number presents, then it returns 1 and if number does not exist, then it returns 0. ExecutionScript code was adopted from the following discussion: https://forums.asp.net/t/1945825.aspx?javascript+check+if+a+string+exists+on+page

For the internal website where I tested it, count returns correct value if the difference between numbers is at least 2, but returns incorrectly when difference is greater than 2.

For a test I used https://www.google.com - for this site, difference between the number needs to be 3 to get the correct value. For example, if nowYearQA = 2030 and pastYearQA = 2029, or pastYearQA = 2028, then countCurrentYearQA gets 0 and countPastYearQA gets 1 - this is incorrect result.

When nowYearQA = 2030 and pastYearQA = 2027, then countCurrentYearQA gets 0 and countPastYearQA gets 0 - this is correct result.

Is there something I am overlooking here? Why is this difference? I understand from this post that "ExecuteScript API does not support Int, and only supports long" - this is the reason I've long cast the variables in the code snippet.

回答1:

The problem with your current approach is that you search the entire markup source for four-digit numeric strings, which are likely to occur somewhere.

I suggest three improvements:

  1. Search in innerText, not in innerHTML. In this way numbers that are part of invisible tags like scripts, are excluded
  2. Target the tag(s) that contain the year numbers specifically. Inspect the markup to find the appropriate criteria for a selector, for example an id value:

    document.getElementByID('yearspan').innerText

  3. search for whole words only, not with the indexOf function. Find an example of how that can be done here: https://stackoverflow.com/a/2232947/1132334