Skip to content

Commit

Permalink
tests: create unit test for useMobile hook
Browse files Browse the repository at this point in the history
  • Loading branch information
rayane-barbosa committed Jun 14, 2024
1 parent 8d21645 commit 3e69ce3
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
50 changes: 50 additions & 0 deletions src/hooks/useIsMobile.test.tsx
Original file line number Diff line number Diff line change
@@ -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)
})
})

0 comments on commit 3e69ce3

Please sign in to comment.