When freezing time you must sync this between the server and the client

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the testing category.

Last Updated: 2024-11-23

I had a system test in Selenium that was supposed to work with a pop-up that displayed only after a certain amount of time.

Here was the test code for triggering it:

def trigger_popup
  travel 5.minutes
  page.execute_script('window.scrollBy(0,1)')
end

The corresponding JavaScript for creating the pop-up was:

startDate = new Date()

window.addEventListener('scroll', function() {
    let secondsOnPage = (new Date() - startDate) / 1000;
    isScrolledFarEnough = window.scrollY > 1000;

    if(!gaveEmail() && !isDismissed() && (isScrolledFarEnough && secondsOnPage > 90)) {
      email_subscribe_modal.modal('show');
    } else {
      email_subscribe_modal.modal('hide');
    }
});

My test did not trigger the JavaScript, however. This was because the time in the Ruby process had no bearing on the time in my JavaScript process. The working solution involved created a script, using Ruby, to modify time in my JavaScript process:

page.execute_script(
  <<-JAVASCRIPT
  currentTime = new Date().getTime();
  window.oldDateClass = Date;

  Date = function (_)
  {
  let seconds = 300
  return new oldDateClass(currentTime + (seconds * 1000));
  };
  Date.now = Date;
  JAVASCRIPT
)