cypress-io / cypress

Fast, easy and reliable testing for anything that runs in a browser.
https://cypress.io
MIT License
47.1k stars 3.19k forks source link

cy.window() to access clipboard immediately results in 'document is not focused' error #28488

Open aosama94 opened 11 months ago

aosama94 commented 11 months ago

Current behavior

I used cy.window() to acces the clipboard, and it doesn't let me do any cypress command till i use cy.wait() and there is no option instead the wait:

    cy.window().then((win) => {
      win.navigator.clipboard.readText().then((data) => {
        // console.log(data);
        cy.wait(1000);
        cy.writeFile('cypress/genericTestData/importedService.json', data);
        cy.log(data);
      });
    });

If i used cy.log() without wait it will throw an error (document is not focused) so there is no way to use any cypress command inside it

if I used cy.get('element').type('test); it will not see this command or will not throw any errors just like it doesn't exist

conclusion: cy.log(somthine). will throw error (document is not focused) cy.get.type. will be considered as not existing command

I just need to get the clipboard text to use it ino an input filed to continue my testing

I hope that you got my point

Desired behavior

Should be any way to not show the error (document is not focused) instead of the cy.wait()!!

Test code to reproduce

    cy.window().then((win) => {
      win.navigator.clipboard.readText().then((data) => {
        // console.log(data);
        cy.wait(1000);
        cy.writeFile('cypress/genericTestData/importedService.json', data);
        cy.log(data);
      });
    });

Cypress Version

"cypress": "^13.6.0

Node version

v20.9.0

Operating System

Version 14.0 (23A344)

Debug Logs

No response

Other

No response

saarimshaikh commented 11 months ago

Can you please specify the path of file in which this code is written?

aosama94 commented 11 months ago

e2e folder for sure /cypress/e2e/services/exportService/exportService.cy.js

and there is another point I forgot to mention

when i write this code in (it) it will not run any cy command inside the the window function it will run only inside beforeEach with wait to prevent error document is not focused

jennifer-shehane commented 11 months ago

@aosama94 We changed some of the behavior around tab focusing in recent versions. I suspect this may have introduced the change in behavior: https://github.com/cypress-io/cypress/pull/28334

I've been unable to reproduce the issue, so want to understand the circumstances for us to address it.

jennifer-shehane commented 11 months ago

Hmm, I found this thread so now I wonder if this has always been a problem and isn't new: https://github.com/cypress-io/cypress/issues/18198 There is a workaround in that issue.

aosama94 commented 11 months ago

This is the full code :

describe('Export Service', () => {
  const service = new ServicesPage();
  const util = new Util();

  before('login', () => {
    Cypress.on('uncaught:exception', () => false);
    util.navigate();
    util.login(loginCredentials.userName.user1, loginCredentials.password);
  });

  it('E2E Service Flow - Export Service', () => {
    Cypress.on('uncaught:exception', () => false);
    util.componentSelect(flowData.id);
    util.getStoredData((text) => {
      util.searchBy(flowData.searchBy.label, text);
    });
    util.editIcon(flowData.component).click();
    service.exportBtn().click();
    cy.get('div.ant-modal-content > div > section > div > div > div.overflow-guard > textarea').type('{esc}', { force: true });
    cy.window().then((win) => {
      win.navigator.clipboard.readText().then((data) => {
        // console.log(data);
        cy.wait(1000);
        cy.writeFile('cypress/genericTestData/importedService.json', data);
        cy.log(data);
      });
    });
  });
  it('E2E Service Flow - Export Service', () => {
    Cypress.on('uncaught:exception', () => false);

  });
});

In above implementation (The cy.window is inside it() ) the results will be like this : look it didn't see the cy.writeFile() command

Screenshot 2023-12-12 at 1 03 34 PM

If we replace the it() with beforeEach() the results will be like this : look it saw the cy.writeFile() command

Screenshot 2023-12-12 at 1 05 45 PM

so it wokrs with beforeEach() and didn't work with it()

and with beforeEach() if I remove the wait(1000) it will throw the folloing error

Screenshot 2023-12-12 at 1 16 49 PM
aosama94 commented 11 months ago

question here

And why wee need a wait ? and what we can use instead of wait here

aosama94 commented 11 months ago

Other thing related to the main code in the above comment

As you see the last it doesn't have any commands inside if i decided to continue my testing at the last it it will throw the following error

Screenshot 2023-12-12 at 1 29 42 PM

I should continue my test in a new spec file !! so this file will only contain beforeEach hook ?!!

bharanidharan439 commented 10 months ago

any improvement in this issue?

johanFuturice commented 9 months ago

Hi - @jennifer-shehane I'm facing similar issues as reported here.

In this case we're writing text to the clipboard, which is then read in the actual test down the line. The issue however seems to be around cy.window() since this fails in the beforeEach() before we can read the clipboard content. The runs always fail with open mode (i.e. headed) when the window is not focused, but never fail in headless mode. I'm running on Windows with Chrome 121. I've upgraded to latest cypress 13.6.4 and this issue persists still (note: had to apply this fix as well https://github.com/cypress-io/cypress/issues/28392)

I've created the simplest possible use case that is fairly generic below. Note that the application of window.focus() after writing to clipboard seems to be the key to hold this together in headless mode (and headed with window focused). Without it the test always breaks with the Document is not focused error. Tried a bit of wait and other ideas but nothing here seems to resolve this.

describe('Create test that reliably fails with Document Not focused', () => {
  beforeEach(() => {
    // Allow clipboard access
    cy.wrap(
      Cypress.automation('remote:debugger:protocol', {
        command: 'Browser.grantPermissions',
        params: {
          permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
          origin: window.location.origin,
        },
      })
    );

    // Write any gibberish to clipbaord
    cy.window().then((window) => {
      window.navigator.clipboard.writeText('gibberish');
      window.focus(); // Important: without this the test will fail also in both headed (with focus) and headless mode
    });
    cy.visit('/');
  });

  it('Should not fail', () => {
    expect(true).to.eq(true);
  });
});

ends up with image

Let me know if I can provide more details.

jennifer-shehane commented 9 months ago

Could you all try to update to 13.6.6 and let us know if you're still experiencing this issue? We fixed an issue in 13.6.5 that was introduced in 13.6.0 and we want to understand if this has also resolved this issue. Thank you!

johanFuturice commented 9 months ago

Updated to 13.6.6 but unfortunately the same issue persists for me (with the same example test as in my prev post). The test only passes if the cypress browser window is focused (or in headless), but unfocused window does not

jennifer-shehane commented 9 months ago

That's unfortunate. 😞

carms-ng commented 7 months ago

Just to note that, updated to 13.7.1, I'm still experiencing the same issue!

trananhchuong commented 3 months ago

I found a solution using navigator.clipboard.writeText instead of calling the function from the window variable.

It worked for me.