clientScript() function in testcafe isn't working on all pages

220 views Asked by At

According to Testcafe's documentation, I should be able to inject a clientScript into all pages: https://testcafe.io/documentation/402843/guides/advanced-guides/inject-client-scripts#add-client-scripts-to-all-tests

I currently have it set up to inject this script so that it can dismiss notifications that pop up in our application which overlay buttons that we need to interact with.

const notifications_div = document.querySelector('.notifications')

if (notifications_div) {
  // Creates the MutationObserver and triggers the callback
  const mutationObserver = new MutationObserver(() => {

    // Checks to see if the style is set to 'block'
    if (notifications_div.style.display == 'block') {
      // Set the dismiss button to a variable each time since the previous will no longer exist.
      let dismiss_button = document.querySelector("a[data-turbo-method='delete']")
      // Click the dismiss button; Timeout is needed to avoid race condition errors.
      setTimeout(() => { dismiss_button.click(); }, 3000);
      // Hide the notifications_div again since it never truly goes away; Timeout is needed to avoid race condition errors.
      setTimeout(() => { notifications_div.style.display = 'none'; }, 3000);
    }

  })
  // Starts the observation of the notifications_div and checks for a change on 'style'
  mutationObserver.observe(notifications_div, {
    attributes: true,
    attributeOldValue: true,
    attributeFilter: ['style']
  })
}

When I run this code in the console and then trigger a notification, it works just fine. When I run a testcafe suite I still end up seeing notifications (that asynchronously pop up), cover the button that I need to interact with, and never close.

When does the code actually get injected? Is it every page load?

Video of the script working fine via the console: https://www.loom.com/share/1a5b96d054a345748e4f018bc56af413

enter image description here

enter image description here

1

There are 1 answers

0
Alex Kamaev On

The Client Script injection should work even after a new page is loaded. The following code snippet demonstrates that the script is injected:

fixture`f`
    .page`http://example.com`;

const clientScript = `
    console.log('location: ' + window.location.href);
`;

test
('My test', async t => {
    await t.navigateTo('http://google.com');
    await t.debug();
})
    .clientScripts({ content: clientScript });


If this code does not help, please create a separate issue in the TestCafe official repository using the following template and share an example where the problem is reproduced: https://github.com/DevExpress/testcafe/issues/new?assignees=&labels=TYPE%3A+bug&template=bug_report.yaml.