When you are dealing with javascript testing frameworks with selenium, when your test fails, you receive useless stack traces.

For example, check out these posts:

link1

link2

This is difficult to debug as it doesn’t show which exact line number caused the test to fail.

It gets even more confusing if the tests are flaky – as in it fails occasionally.

One way to debug that I’ve found out was to use monkeypatch.

The methods you are using gets monkey patched so stack trace is saved before calling the function like this:

let stack = [];

let oldFindElement = driver.findElement;
driver.findElement = function() {
  let stackError = new Error();
  
  stack.push(stackError);

  try {
    return oldFindElement.apply(page.X, arguments);
  } catch (e) {
    console.log(stack[stack.length - 1]); // you can see the current stack trace here
    throw e;
  }
};

Of course, you can loop through the functions to monkey patch for most of the driver’s functions.

I’ve found this to be very useful for debugging as we can now tell the exact line of failure.