From 3e69ce38e04daa5e5542e7ccc81074182ecbc356 Mon Sep 17 00:00:00 2001 From: Rayane-Barbosa Date: Thu, 13 Jun 2024 21:33:55 -0300 Subject: [PATCH] tests: create unit test for useMobile hook --- package.json | 1 + src/hooks/useIsMobile.test.tsx | 50 ++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 src/hooks/useIsMobile.test.tsx diff --git a/package.json b/package.json index 048b349..9d48ff5 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,7 @@ "@rocketseat/eslint-config": "^2.2.2", "@testing-library/jest-dom": "^6.4.5", "@testing-library/react": "^15.0.7", + "@testing-library/react-hooks": "^8.0.1", "@testing-library/user-event": "^14.5.2", "@types/jest": "^29.5.12", "@types/mocha": "^10.0.6", diff --git a/src/hooks/useIsMobile.test.tsx b/src/hooks/useIsMobile.test.tsx new file mode 100644 index 0000000..30599e5 --- /dev/null +++ b/src/hooks/useIsMobile.test.tsx @@ -0,0 +1,50 @@ +import '@testing-library/jest-dom' +import { renderHook } from '@testing-library/react-hooks' +import { useIsMobile } from './useIsMobile' + +describe('useIsMobile', () => { + beforeAll(() => { + Object.defineProperty(window, 'matchMedia', { + writable: true, + value: jest.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: jest.fn(), + removeListener: jest.fn(), + addEventListener: jest.fn(), + removeEventListener: jest.fn(), + dispatchEvent: jest.fn(), + })), + }) + }) + test('returns true when screen width is less than or equal to mobileScreenSize', () => { + window.matchMedia = jest.fn().mockImplementation((query) => ({ + matches: true, + media: query, + onchange: null, + addListener: jest.fn(), + removeListener: jest.fn(), + addEventListener: jest.fn(), + removeEventListener: jest.fn(), + dispatchEvent: jest.fn(), + })) + const { result } = renderHook(() => useIsMobile()) + expect(result.current).toBe(true) + }) + + test('returns false when screen width is greater than mobileScreenSize', () => { + window.matchMedia = jest.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: jest.fn(), + removeListener: jest.fn(), + addEventListener: jest.fn(), + removeEventListener: jest.fn(), + dispatchEvent: jest.fn(), + })) + const { result } = renderHook(() => useIsMobile()) + expect(result.current).toBe(false) + }) +})