cypress-io / cypress

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

Support to detect touch supported devices #8907

Open abhinavpreetu opened 4 years ago

abhinavpreetu commented 4 years ago

What would you like?

Can we add support for pointer media queries

Why is this needed?

I am using window.matchMedia to detect devices with a coarse primary pointer and then perform some action if it returns true. I tried using cy.viewport() but it does not simulate a touch supported device

atomanyih commented 3 years ago

It seems like google chrome is able to change to (pointer: coarse) when you are using the devTools device toolbar. I wonder if there is a way to enable that through chrome command line options 🤔

Edit: this seems to work:

Cypress.automation("remote:debugger:protocol", {
  command: 'Emulation.setTouchEmulationEnabled',
  params: {
    enabled: true
  }
})
matthewnewman43 commented 1 year ago

Was able to mock out this behavior through a custom command! This also does a clean enough job of cleaning itself up as well.

export default function (callback: () => void): void {
  cy.log('Mocking as touch device');

  // Mock match media to return true
  let originalMatchMedia;
  cy.window({ log: false }).then((win) => {
    originalMatchMedia = win.matchMedia;

    Object.defineProperty(win, 'matchMedia', {
      value: (arg) => ({
        matches: !!arg.includes('(pointer: coarse)'),
        addListener: () => {},
        removeListener: () => {},
      }),
    });
  });

  callback();

  // Reset to original window match media
  cy.window({ log: false }).then((win) =>
    Object.defineProperty(win, 'matchMedia', { value: originalMatchMedia }),
  );
}