How to Simulate and Test Touch Events in JS Apps?

Content verified by Anycode AI
July 21, 2024
Testing touch events in JavaScript applications is very challenging. Unlike regular mouse events, touch events include contact points, gestures, and even some device-specific behaviors. This leads to potential risks of different user experiences among devices and browsers if not handled accordingly. Our guide solves the problem of properly emulating and testing touch events in JS apps. The package provides users with a clear, organized methodology for developing stable tests that can imitate real-world touch events. With this, you'll be able to ensure your application is correctly handling various touch scenarios—taps, complex multi-touch gestures, and everything in between. Proper touch event testing will help in the early detection of bugs, increase the responsiveness of an app, and enrich overall user experience on Touch-enabled devices. Be it mobile web apps, hybrid applications, or touch-friendly desktop sites, mastering touch event simulation is important for delivering solid and user-friendly interfaces.

Simulating and testing touch events in JavaScript apps is super important. Ensures your app runs smoothly on touch devices like smartphones and tablets. So, let's dive into some methods to test and simulate touch events, manually and programmatically. We’ll check out:

  • DevTools in Modern Browsers
  • Programmatically Simulating Touch Events
  • Unit Testing with Jest and Testing Library

DevTools in Modern Browsers

Modern browsers have some handy tools built-in to simulate touch events.

Chrome DevTools

  1. Open DevTools: Right-click on your page, select "Inspect," or hit Ctrl+Shift+I (Windows) or Cmd+Opt+I (Mac).
  2. Toggle Device Toolbar: Click the toggle icon or press Ctrl+Shift+M (Windows) or Cmd+Opt+M (Mac) to enter responsive design mode.
  3. Select a Device: Pick a device from the list or set custom dimensions.
  4. Simulate Touch Events: The device toolbar will by default simulate touch events. Use your mouse to interact as if it were a touch screen. Nice, right?

Firefox DevTools

  1. Open DevTools: Right-click your page and select "Inspect Element," or hit Ctrl+Shift+I (Windows) or Cmd+Opt+I (Mac).
  2. Toggle Responsive Design Mode: Click the responsive design icon or press Ctrl+Shift+M (Windows) or Cmd+Opt+M (Mac).
  3. Select a Device: Choose from dropdown menu and voila!

Simulating Touch Events Programmatically

Wanna go deeper? Simulate touch events with JavaScript for more control.

  1. Touch Start Event: Starts when a finger touches the screen.
  2. Touch Move Event: Moves when a finger slides across the screen.
  3. Touch End Event: Ends when the finger lifts off the screen.

Example Code: Simulating a Touch Event

Here’s how you do it:

function simulateTouchEvent(type, target, opts = {}) {
    const touchObj = new Touch({
        identifier: Date.now(),
        target: target,
        clientX: opts.clientX || 0,
        clientY: opts.clientY || 0,
        screenX: opts.screenX || 0,
        screenY: opts.screenY || 0,
        radiusX: opts.radiusX || 1,
        radiusY: opts.radiusY || 1,
        rotationAngle: opts.rotationAngle || 0,
        force: opts.force || 1
    });

    const touchEvent = new TouchEvent(type, {
        touches: [touchObj],
        targetTouches: [],
        changedTouches: [touchObj],
        bubbles: true,
        cancelable: true,
        composed: true
    });

    target.dispatchEvent(touchEvent);
}

// Usage
const myElement = document.getElementById('myElement');

// Simulate touch start
simulateTouchEvent('touchstart', myElement, { clientX: 50, clientY: 60 });

// Simulate touch move
simulateTouchEvent('touchmove', myElement, { clientX: 70, clientY: 80 });

// Simulate touch end
simulateTouchEvent('touchend', myElement, { clientX: 70, clientY: 80 });

Unit Testing Touch Events with Jest and Testing Library

Automate your touch event tests with Jest and Testing Library (like React Testing Library).

Install Dependencies

First, get the required libraries.

npm install --save @testing-library/react @testing-library/jest-dom jest

Example Code: Unit Testing Touch Events

Here’s a React component and how you can test it using Jest and Testing Library.

MyComponent.js

import React from 'react';

function MyComponent() {
    const handleTouchStart = (event) => {
        console.log('Touch Start:', event.touches[0].clientX, event.touches[0].clientY);
    };

    const handleTouchMove = (event) => {
        console.log('Touch Move:', event.touches[0].clientX, event.touches[0].clientY);
    };

    const handleTouchEnd = (event) => {
        console.log('Touch End');
    };

    return (
        <div
            data-testid="touchable-element"
            onTouchStart={handleTouchStart}
            onTouchMove={handleTouchMove}
            onTouchEnd={handleTouchEnd}
            style={{ width: '200px', height: '200px', background: 'lightblue' }}
        >
            Touch Me
        </div>
    );
}

export default MyComponent;

MyComponent.test.js

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import MyComponent from './MyComponent';

test('handles touch events', () => {
    const { getByTestId } = render(<MyComponent />);
    const touchableElement = getByTestId('touchable-element');

    // Simulate touch start
    fireEvent.touchStart(touchableElement, {
        touches: [{ clientX: 50, clientY: 60 }],
    });

    // Simulate touch move
    fireEvent.touchMove(touchableElement, {
        touches: [{ clientX: 70, clientY: 80 }],
    });

    // Simulate touch end
    fireEvent.touchEnd(touchableElement, {
        touches: [{ clientX: 70, clientY: 80 }],
    });

    // Custom assertions can be added here if needed
});

And there you have it! This setup pretty much covers the basics to help you test touch interactions in your apps!

Have any questions?
Our CEO and CTO are happy to
answer them personally.
Get Beta Access
Anubis Watal
CTO at Anycode
Alex Hudym
CEO at Anycode