Open felipexperto opened 3 months ago
Code
import { useEffect, useState } from 'react'; function useTouchDevice() { const [isTouch, setIsTouch] = useState(false); useEffect(() => { const checkTouchDevice = () => { setIsTouch("ontouchstart" in window || navigator.maxTouchPoints > 0); }; checkTouchDevice(); }, []); return isTouch; } export default useTouchDevice;
Tests:
import { renderHook } from "@testing-library/react-hooks"; import useTouchDevice from "./useTouchDevice"; describe("[Hooks] useTouchDevice", () => { describe("ontouchstart", () => { it("should detect non-touch device", () => { delete window.ontouchstart; Object.defineProperty(navigator, "maxTouchPoints", { value: 0, writable: true, }); const { result } = renderHook(() => useTouchDevice()); expect(result.current).toBe(false); }); it("should detect touch device based on ontouchstart", () => { Object.defineProperty(window, "ontouchstart", { value: true, writable: true, }); const { result } = renderHook(() => useTouchDevice()); expect(result.current).toBe(true); }); }); describe("maxTouchPoints", () => { it("should detect touch device based on maxTouchPoints", () => { delete window.ontouchstart; Object.defineProperty(navigator, "maxTouchPoints", { value: 1, writable: true, }); const { result } = renderHook(() => useTouchDevice()); expect(result.current).toBe(true); }); }); });
Code
Tests: