Skip to content

Commit

Permalink
test: include main functionalities testing
Browse files Browse the repository at this point in the history
  • Loading branch information
Dawntraoz committed Sep 23, 2024
1 parent 2b6e0a0 commit 740c53a
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/* eslint-disable functional/immutable-data */
import { createKeydownEscListener } from './createKeydownEscListener'

describe('createKeydownEscListener', () => {
let addEventListenerSpy: vi.SpyInstance
let removeEventListenerSpy: vi.SpyInstance
const escapeEvent = new KeyboardEvent('keydown', { key: 'Escape' })

beforeEach(() => {
addEventListenerSpy = vi.spyOn(document, 'addEventListener')
removeEventListenerSpy = vi.spyOn(document, 'removeEventListener')
})

afterEach(() => {
vi.restoreAllMocks()
})

it('should call addEventListener with keydown and handleEsc', () => {
const mockOnPressed = vi.fn()

createKeydownEscListener(mockOnPressed)

expect(addEventListenerSpy).toHaveBeenCalledWith(
'keydown',
expect.any(Function),
)
})

it('should trigger onPressed when Escape key is pressed', () => {
const mockOnPressed = vi.fn()

const removeListener = createKeydownEscListener(mockOnPressed)

document.dispatchEvent(escapeEvent)

expect(mockOnPressed).toHaveBeenCalled()

removeListener()

expect(removeEventListenerSpy).toHaveBeenCalledWith(
'keydown',
expect.any(Function),
)
})

it('should not trigger onPressed when a non-Escape key is pressed', () => {
const mockOnPressed = vi.fn()

createKeydownEscListener(mockOnPressed)

const enterEvent = new KeyboardEvent('keydown', { key: 'Enter' })
document.dispatchEvent(enterEvent)

expect(mockOnPressed).not.toHaveBeenCalled()
})

it('should not trigger onPressed when the cleanup function is called', () => {
const mockOnPressed = vi.fn()
const removeListener = createKeydownEscListener(mockOnPressed)

removeListener()

expect(removeEventListenerSpy).toHaveBeenCalledWith(
'keydown',
expect.any(Function),
)

document.dispatchEvent(escapeEvent)

expect(mockOnPressed).not.toHaveBeenCalled()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
* @returns function for cleaning up side effects
*/

export const createKeydownEscListener = (onChange: () => void) => {
export const createKeydownEscListener = (onPressed: () => void) => {
const handleEsc = (event: KeyboardEvent) => {
const key = event.key
if (key === 'Escape') {
onChange()
onPressed()
}
}

Expand Down

0 comments on commit 740c53a

Please sign in to comment.